From 228bdd703f3e4f6610d2b518cd5fd9904532c3ed Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Thu, 25 Jan 2024 13:28:08 -0800 Subject: [PATCH 001/103] Extract code snippets, move ISO references to snippets, update msdn links to learn.microsoft (#305) * closes #265 (working-with-wordprocessingml-tables.md) * closes #264 (working-with-runs.md) * closes #263 (working-with-paragraphs.md) * closes #299 (xmlns should use http instead of https in multiple files) * closes #262 (structure-of-a-wordprocessingml-document.md) * closes #301 (Ensure we're not referencing specific versions) * closes #261 (how-to-validate-a-word-processing-document.md) * closes #239 (how-to-set-the-font-for-a-text-run.md) * closes #302 (Convert MSDN links to microsoft.learn) * closes #304 (Extract ISO/IEC 29500 references to snippet) * make https://learn.microsoft.com links relative --- .gitignore | 4 +- docs/about-the-open-xml-sdk.md | 4 +- ...to-add-a-new-document-part-to-a-package.md | 2 +- ...ackage-part-to-a-document-part-in-a-dif.md | 10 +- docs/general/how-to-create-a-package.md | 10 +- ...tents-of-a-document-part-from-a-package.md | 10 +- ...o-remove-a-document-part-from-a-package.md | 7 +- ...heme-part-in-a-word-processing-document.md | 18 +-- ...rch-and-replace-text-in-a-document-part.md | 6 +- .../introduction-to-markup-compatibility.md | 10 +- docs/includes/iso-iec-29500-link.md | 1 + docs/includes/iso-iec-29500-version.md | 1 + docs/includes/presentation/structure.md | 14 +- docs/includes/spreadsheet/structure.md | 10 +- .../word/packages-and-document-parts.md | 2 +- docs/includes/word/structure.md | 14 +- docs/open-xml-sdk.md | 10 +- .../how-to-apply-a-theme-to-a-presentation.md | 8 +- ...fill-color-of-a-shape-in-a-presentation.md | 4 +- ...ation-document-by-providing-a-file-name.md | 30 ++--- ...w-to-delete-a-slide-from-a-presentation.md | 2 +- ...or-from-all-the-slides-in-a-presentatio.md | 8 +- ...e-external-hyperlinks-in-a-presentation.md | 9 +- ...l-the-text-in-a-slide-in-a-presentation.md | 4 +- ...he-text-in-all-slides-in-a-presentation.md | 6 +- ...les-of-all-the-slides-in-a-presentation.md | 6 +- ...-insert-a-new-slide-into-a-presentation.md | 4 +- ...agraph-from-one-presentation-to-another.md | 8 +- ...ide-to-a-new-position-in-a-presentation.md | 4 +- ...sentation-document-for-read-only-access.md | 12 +- ...er-of-slides-in-a-presentation-document.md | 10 +- .../structure-of-a-presentationml-document.md | 62 ++++----- docs/presentation/working-with-animation.md | 10 +- docs/presentation/working-with-comments.md | 34 ++--- .../working-with-handout-master-slides.md | 48 +++---- .../presentation/working-with-notes-slides.md | 60 ++++----- .../working-with-presentation-slides.md | 62 ++++----- .../working-with-presentations.md | 84 ++++++------ .../working-with-slide-layouts.md | 58 ++++---- .../working-with-slide-masters.md | 62 ++++----- ...add-custom-ui-to-a-spreadsheet-document.md | 7 +- ...ange-of-cells-in-a-spreadsheet-document.md | 6 +- ...sheet-document-by-providing-a-file-name.md | 18 +-- ...elete-text-from-a-cell-in-a-spreadsheet.md | 6 +- ...o-get-a-column-heading-in-a-spreadsheet.md | 10 +- ...ow-to-insert-a-chart-into-a-spreadsheet.md | 22 +-- ...nsert-text-into-a-cell-in-a-spreadsheet.md | 16 +-- ...rge-two-adjacent-cells-in-a-spreadsheet.md | 2 +- ...readsheet-document-for-read-only-access.md | 26 ++-- ...en-a-spreadsheet-document-from-a-stream.md | 14 +- ...ry-of-all-named-ranges-in-a-spreadsheet.md | 5 +- ...hidden-rows-or-columns-in-a-spreadsheet.md | 10 +- ...-the-hidden-worksheets-in-a-spreadsheet.md | 4 +- ...list-of-the-worksheets-in-a-spreadsheet.md | 10 +- ...ve-the-values-of-cells-in-a-spreadsheet.md | 28 ++-- .../structure-of-a-spreadsheetml-document.md | 28 ++-- .../working-with-conditional-formatting.md | 22 +-- docs/spreadsheet/working-with-formulas.md | 10 +- docs/spreadsheet/working-with-pivottables.md | 10 +- docs/spreadsheet/working-with-sheets.md | 38 +++--- docs/spreadsheet/working-with-tables.md | 10 +- .../working-with-the-calculation-chain.md | 8 +- .../working-with-the-shared-string-table.md | 14 +- ...revisions-in-a-word-processing-document.md | 26 ++-- ...paragraph-in-a-word-processing-document.md | 28 ++-- ...n-a-table-in-a-word-processing-document.md | 8 +- ...ientation-of-a-word-processing-document.md | 21 ++- ...t-from-the-docm-to-the-docx-file-format.md | 6 +- ...ssing-document-by-providing-a-file-name.md | 10 +- ...ter-style-to-a-word-processing-document.md | 16 +-- ...aph-style-to-a-word-processing-document.md | 20 +-- ...ic-author-in-a-word-processing-document.md | 20 +-- ...-styles-from-a-word-processing-document.md | 25 ++-- ...comment-into-a-word-processing-document.md | 38 +++--- ...picture-into-a-word-processing-document.md | 13 +- ...a-table-into-a-word-processing-document.md | 26 ++-- ...rocessing-document-for-read-only-access.md | 10 +- ...-word-processing-document-from-a-stream.md | 4 +- ...-add-text-to-a-word-processing-document.md | 4 +- ...en-text-from-a-word-processing-document.md | 18 +-- ...footers-from-a-word-processing-document.md | 18 +-- ...he-header-in-a-word-processing-document.md | 6 +- ...les-parts-in-a-word-processing-document.md | 28 ++-- ...-values-from-a-word-processing-document.md | 2 +- ...omments-from-a-word-processing-document.md | 14 +- ...-property-in-a-word-processing-document.md | 8 +- .../how-to-set-the-font-for-a-text-run.md | 125 +++--------------- ...-to-validate-a-word-processing-document.md | 40 +----- ...tructure-of-a-wordprocessingml-document.md | 70 +++++----- docs/word/working-with-paragraphs.md | 33 +++-- docs/word/working-with-runs.md | 27 ++-- .../working-with-wordprocessingml-tables.md | 120 +++-------------- samples/samples.sln | 16 ++- .../word/insert_table_in_doc/cs/Program.cs | 68 ++++++++++ .../cs/insert_table_in_doc_cs.csproj | 1 + .../word/insert_table_in_doc/vb/Program.vb | 59 +++++++++ .../vb/insert_table_in_doc_vb.vbproj | 1 + .../replace_the_styles_parts/vb/Program.vb | 2 +- .../set_the_font_for_a_text_run/cs/Program.cs | 11 +- .../set_the_font_for_a_text_run/vb/Program.vb | 13 +- .../cs/Program.cs | 8 +- .../vb/Program.vb | 7 +- samples/word/validate/cs/Program.cs | 7 +- samples/word/validate/vb/Program.vb | 8 +- .../working_with_paragraphs/cs/Program.cs | 5 +- .../working_with_paragraphs/vb/Program.vb | 5 +- samples/word/working_with_runs/cs/Program.cs | 5 +- samples/word/working_with_runs/vb/Program.vb | 5 +- .../word/working_with_tables/cs/Program.cs | 68 ++++++++++ .../cs/working_with_tables_cs.csproj | 1 + .../word/working_with_tables/vb/Program.vb | 59 +++++++++ .../vb/working_with_tables_vb.vbproj | 1 + 112 files changed, 1141 insertions(+), 1045 deletions(-) create mode 100644 docs/includes/iso-iec-29500-link.md create mode 100644 docs/includes/iso-iec-29500-version.md create mode 100644 samples/word/insert_table_in_doc/cs/Program.cs create mode 100644 samples/word/insert_table_in_doc/cs/insert_table_in_doc_cs.csproj create mode 100644 samples/word/insert_table_in_doc/vb/Program.vb create mode 100644 samples/word/insert_table_in_doc/vb/insert_table_in_doc_vb.vbproj create mode 100644 samples/word/working_with_tables/cs/Program.cs create mode 100644 samples/word/working_with_tables/cs/working_with_tables_cs.csproj create mode 100644 samples/word/working_with_tables/vb/Program.vb create mode 100644 samples/word/working_with_tables/vb/working_with_tables_vb.vbproj diff --git a/.gitignore b/.gitignore index 4f4f50e5..f14cbd54 100644 --- a/.gitignore +++ b/.gitignore @@ -287,4 +287,6 @@ __pycache__/ *.odx.cs *.xsd.cs -docs/open-xml-docs/ \ No newline at end of file +docs/open-xml-docs/ +samples/**/Properties/**/* +samples/**/My\ Project/**/* diff --git a/docs/about-the-open-xml-sdk.md b/docs/about-the-open-xml-sdk.md index 6a12d435..6ab0ad18 100644 --- a/docs/about-the-open-xml-sdk.md +++ b/docs/about-the-open-xml-sdk.md @@ -62,11 +62,11 @@ The SDK supports the following common tasks/scenarios: ## Open XML SDK for Office -The Open XML SDK provides the namespaces and members to support the Microsoft Office 2013. The Open XML SDK can also read ISO/IEC 29500 Strict Format files. The Strict format is a subset of the Transitional format that does not include legacy features - this makes it theoretically easier for a new implementer to support since it has a smaller technical footprint. +The Open XML SDK provides the namespaces and members to support the Microsoft Office. The Open XML SDK can also read ISO/IEC 29500 Strict Format files. The Strict format is a subset of the Transitional format that does not include legacy features - this makes it theoretically easier for a new implementer to support since it has a smaller technical footprint. The SDK supports the following common tasks/scenarios: -- **Support of Office 2013 Preview file format** In addition to the Open XML SDK for Microsoft Office classes, Open XML SDK provides new classes that enable you to write and build applications to manipulate Open XML file extensions of the new Office 2013 features. +- **Support of Office Preview file format** In addition to the Open XML SDK for Microsoft Office classes, Open XML SDK provides new classes that enable you to write and build applications to manipulate Open XML file extensions of the new Office features. - **Reads ISO Strict Document File** Open XML SDK can read ISO/IEC 29500 Strict Format files. When the Open XML SDK API opens a Strict Format file, each Open XML part in the file is loaded to an **OpenXmlPart** class of the Open XML SDK by mapping `https://purl.oclc.org/ooxml/` namespaces to the corresponding `https://schemas.openxmlformats.org/` namespaces. - **Fixes to the Open XML SDK for Microsoft Office** Open XML SDK includes fixes to known issues in the Open XML SDK for Microsoft Office. These include lost whitespaces in PowerPoint presentations and an issue with the Custom UI in Word documents where a specified argument was reported as being out of the range of valid values. 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 40021a8f..46e18fc8 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 @@ -21,7 +21,7 @@ This topic shows how to use the classes in the Open XML SDK for Office to add a ## Get a WordprocessingDocument object -The code starts with opening a package file by passing a file name to one of the overloaded **[Open()](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.open.aspx)** methods of the **[DocumentFormat.OpenXml.Packaging.WordprocessingDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.aspx)** 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. +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 of the **[DocumentFormat.OpenXml.Packaging.WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument)** 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 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 3429e8d8..272ba2ab 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 @@ -30,10 +30,10 @@ programmatically. -------------------------------------------------------------------------------- ## Getting a WordprocessingDocument Object -To open an existing document, instantiate the [WordprocessingDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.aspx) class as shown in +To open an existing document, instantiate the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) class as shown in the following two **using** statements. In the same statement, you open the word processing file with the specified -file name by using the [Open](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.open.aspx) method, with the Boolean parameter. +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 order to enable editing the document. @@ -78,7 +78,7 @@ long as you use **using**. -------------------------------------------------------------------------------- ## The Theme Part The theme part contains information about the color, font, and format of -a document. It is defined in the [ISO/IEC 29500](https://www.iso.org/standard/71691.html) specification as +a document. It is defined in the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification as follows. An instance of this part type contains information about a document's @@ -110,7 +110,7 @@ is stored in the ZIP item theme/theme1.xml: ``` -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] -------------------------------------------------------------------------------- @@ -191,7 +191,7 @@ following example, which copies the theme part from "MyPkg4.docx" to > [!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 2013, 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 (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. After running the program, you can inspect the file "MyPkg3.docx" to see the copied theme from the file "MyPkg4.docx." diff --git a/docs/general/how-to-create-a-package.md b/docs/general/how-to-create-a-package.md index 5c28f447..0aa2c48b 100644 --- a/docs/general/how-to-create-a-package.md +++ b/docs/general/how-to-create-a-package.md @@ -26,21 +26,21 @@ from content in the form of **WordprocessingML** XML markup. ## Getting a WordprocessingDocument Object -In the Open XML SDK, the [WordprocessingDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.aspx) class represents a Word document package. To create a Word document, you create an instance +In the Open XML SDK, the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) class represents a Word document package. To create a Word document, you create an instance of the **WordprocessingDocument** 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. -To create the class instance you call the [Create(String, WordprocessingDocumentType)](https://msdn.microsoft.com/library/office/cc535610.aspx) +To create the class instance you call the [Create(String, WordprocessingDocumentType)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.create) 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 takes a full path string that represents the document that you want to create. The second -parameter is a member of the [WordprocessingDocumentType](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessingdocumenttype.aspx) enumeration. +parameter is a member of the [WordprocessingDocumentType](/dotnet/api/documentformat.openxml.wordprocessingdocumenttype) enumeration. This parameter represents the type of document. For example, there is a -different member of the [WordProcessingDocumentType](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessingdocumenttype.aspx) enumeration for each +different member of the [WordProcessingDocumentType](/dotnet/api/documentformat.openxml.wordprocessingdocumenttype) enumeration for each of document, template, and the macro enabled variety of document and template. @@ -75,7 +75,7 @@ automatically saves and closes the object as part of its **System.IDisposable** long as you use **using**. Once you have created the Word document package, you can add parts to -it. To add the main document part you call the [AddMainDocumentPart()](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.addmaindocumentpart.aspx) method of the **WordprocessingDocument** class. Having done that, +it. To add the main document part you call the [AddMainDocumentPart()](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.addmaindocumentpart) method of the **WordprocessingDocument** class. Having done that, you can set about adding the document structure and text. [!include[Structure](../includes/word/structure.md)] 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 c092e0be..8f3cb980 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 @@ -29,8 +29,8 @@ 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()](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.open.aspx) methods (Visual Basic .NET Shared -method or C\# static method) of the [WordprocessingDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.aspx) class that takes a +one of the overloaded [Open()](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) methods (Visual Basic .NET Shared +method or C\# static method) of the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) 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 @@ -75,7 +75,7 @@ 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 -from the [ISO/IEC 29500](https://www.iso.org/standard/71691.html) +from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification can be useful when working with this element. This element specifies all of the comments defined in the current @@ -95,7 +95,7 @@ document: The **comments** element contains the single comment specified by this document in this example. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] The following XML schema fragment defines the contents of this element. @@ -197,4 +197,4 @@ Following is the complete code example in both C\# and Visual Basic. [Open XML SDK class library -reference](https://msdn.microsoft.com/library/36c8a76e-ce1b-5959-7e85-5d77db7f46d6(Office.15).aspx) +reference](/office/open-xml/open-xml-sdk) 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 77742ba0..52876957 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 @@ -29,7 +29,7 @@ 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()](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.open.aspx) methods of the [DocumentFormat.OpenXml.Packaging.WordprocessingDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.aspx) +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) 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 @@ -72,8 +72,7 @@ long as you use **using**. -------------------------------------------------------------------------------- ## Settings Element -The following text from the [ISO/IEC -29500](https://www.iso.org/standard/71691.html) specification +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. > This element specifies the settings that are applied to a @@ -95,7 +94,7 @@ 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. > -> © ISO/IEC29500: 2008. +> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] -------------------------------------------------------------------------------- diff --git a/docs/general/how-to-replace-the-theme-part-in-a-word-processing-document.md b/docs/general/how-to-replace-the-theme-part-in-a-word-processing-document.md index 8e86f9c7..7b3406c3 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 @@ -26,10 +26,10 @@ document. ## Getting a WordprocessingDocument Object In the sample code, you start by opening the word processing file by -instantiating the [WordprocessingDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.aspx) class as shown in +instantiating the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) class as shown in the following **using** statement. In the same statement, you open the word processing file *document* by using the -[Open](https://msdn.microsoft.com/library/office/cc562234.aspx) method, with the Boolean parameter set +[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) @@ -78,7 +78,7 @@ in your computer. The theme element constitutes 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 [ISO/IEC 29500](https://www.iso.org/standard/71691.html) specification can +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. This element defines the root level complex type associated with a @@ -97,17 +97,17 @@ In this example, we see how a theme can affect font, colors, backgrounds, fills, and effects for different objects in a presentation. *end example*] -© ISO/IEC29500: 2008. +© [!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](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.customcolorlist.aspx) |Custom Color List | -| extLst | [ExtensionList](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.extensionlist.aspx) | Extension List | -| extraClrSchemeLst | [ExtraColorSchemeList](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.theme.extracolorschemelist.aspx) | Extra Color Scheme List | -| objectDefaults | [ObjectDefaults](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.theme.objectdefaults.aspx) | Object Defaults | -| themeElements | [ThemeElements](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.theme.themeelements.aspx) | Theme Elements | +| 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 | The following XML Schema fragment defines the four parts of the theme element. The **themeElements** element is the 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 1cdc9569..eb2616ab 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 @@ -29,10 +29,10 @@ processing document. --------------------------------------------------------------------------------- ## Getting a WordprocessingDocument Object In the sample code, you start by opening the word processing file by -instantiating the **[WordprocessingDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.aspx)** class as shown in +instantiating the **[WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument)** class as shown in the following **using** statement. In the same statement, you open the word processing file *document* by using the -**[Open](https://msdn.microsoft.com/library/office/cc562234.aspx)** method, with the Boolean parameter set +**[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) @@ -111,4 +111,4 @@ The following is the complete sample code in both C\# and Visual Basic. - [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) -[Regular Expressions](https://msdn.microsoft.com/library/hs600312.aspx) +[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 e9fcd5ac..549dd965 100644 --- a/docs/general/introduction-to-markup-compatibility.md +++ b/docs/general/introduction-to-markup-compatibility.md @@ -50,13 +50,13 @@ The Open XML SDK support for markup compatibility comes primarily in the form of ## 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](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.opensettings.aspx)** 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](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.opensettings.markupcompatibilityprocesssettings.aspx)** property, determines how markup compatibility elements and attributes are processed. You set the property to an instance of the **[MarkupCompatibilityProcessSettings](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.markupcompatibilityprocesssettings.aspx)** 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 **[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. The class has the following properties: -- **[ProcessMode](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.markupcompatibilityprocesssettings.processmode.aspx)** - Determines the parts that are preprocessed. +- **[ProcessMode](/dotnet/api/documentformat.openxml.packaging.markupcompatibilityprocesssettings.processmode)** - Determines the parts that are preprocessed. -- **[TargetFileFormatVersions](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.markupcompatibilityprocesssettings.targetfileformatversions.aspx)** - Specifies the context that applies to preprocessing. +- **[TargetFileFormatVersions](/dotnet/api/documentformat.openxml.packaging.markupcompatibilityprocesssettings.targetfileformatversions)** - 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. @@ -93,7 +93,7 @@ The **ProcessMode** property determines the parts to be preprocessed. The conten ## Understand process mode -The process mode specifies which document parts should be preprocessed. You set this property to a member of the **[MarkupCompatibilityProcessMode](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.markupcompatibilityprocessmode.aspx)** 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 **[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. 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. @@ -101,7 +101,7 @@ Finally, there is **ProcessAllParts**, which specifies what the name implies. Wh ## 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](https://msdn.microsoft.com/library/office/documentformat.openxml.fileformatversions.aspx)** enumeration. +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 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. diff --git a/docs/includes/iso-iec-29500-link.md b/docs/includes/iso-iec-29500-link.md new file mode 100644 index 00000000..bec1b3d5 --- /dev/null +++ b/docs/includes/iso-iec-29500-link.md @@ -0,0 +1 @@ +[ISO/IEC 29500](https://www.iso.org/standard/71691.html) \ No newline at end of file diff --git a/docs/includes/iso-iec-29500-version.md b/docs/includes/iso-iec-29500-version.md new file mode 100644 index 00000000..e9607094 --- /dev/null +++ b/docs/includes/iso-iec-29500-version.md @@ -0,0 +1 @@ +ISO/IEC 29500: 2016 \ No newline at end of file diff --git a/docs/includes/presentation/structure.md b/docs/includes/presentation/structure.md index a1d15f8a..ba3d3091 100644 --- a/docs/includes/presentation/structure.md +++ b/docs/includes/presentation/structure.md @@ -2,7 +2,7 @@ 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 [ISO/IEC 29500](https://www.iso.org/standard/71691.html) specification +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. > The main part of a **PresentationML** package @@ -33,7 +33,7 @@ introduces the overall form of a **PresentationML** package. > parts. For example, all comments in a document are stored in one > comment part while each slide has its own part. > -> © ISO/IEC29500: 2008. +> [!include[ISO/IEC 29500 version](../iso-iec-29500-version.md)] The following XML code example represents a presentation that contains two slides denoted by the IDs 267 and 256. @@ -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](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.aspx) +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 the **sld**, **sldLayout**, **sldMaster**, and **notesMaster** elements. | PresentationML Element | Open XML SDK Class | Description | |---|---|---| -| sld | [Slide](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.slide.aspx) | Presentation Slide. It is the root element of SlidePart. | -| sldLayout | [SlideLayout](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.slidelayout.aspx) | Slide Layout. It is the root element of SlideLayoutPart. | -| sldMaster | [SlideMaster](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.slidemaster.aspx) | Slide Master. It is the root element of SlideMasterPart. | -| notesMaster | [NotesMaster](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.notesmaster.aspx) | Notes Master (or handoutMaster). It is the root element of NotesMasterPart. | \ No newline at end of file +| 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 diff --git a/docs/includes/spreadsheet/structure.md b/docs/includes/spreadsheet/structure.md index 3866d007..51b9e03e 100644 --- a/docs/includes/spreadsheet/structure.md +++ b/docs/includes/spreadsheet/structure.md @@ -1,10 +1,10 @@ ## Basic structure of a spreadsheetML document -The basic document structure of a **SpreadsheetML** document consists of the [Sheets](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheets.aspx) and [Sheet](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheet.aspx) elements, which reference the worksheets in the workbook. A separate XML file is created for each worksheet. For example, the **SpreadsheetML** for a [Workbook](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.workbook.aspx) 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 [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. ```xml - + @@ -13,8 +13,8 @@ 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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheetdata.aspx) represents the cell table and contains -one or more [Row](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.row.aspx) elements. A **row** contains one or more [Cell](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.cell.aspx) elements. Each cell contains a [CellValue](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.cellvalue.aspx) element that represents the value +[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** 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 @@ -42,7 +42,7 @@ the **workbook**, **sheets**, **sheet**, **worksheet**, and **sheetData** elemen | **SpreadsheetML Element** | **Open XML SDK Class** | **Description** | |:---|:---|:---| | workbook | DocumentFormat.OpenXML.Spreadsheet.Workbook | The root element for the main document part. | -| sheets | DocumentFormat.OpenXML.Spreadsheet.Sheets | The container for the block level structures such as sheet, fileVersion, and others specified in the [ISO/IEC 29500](https://www.iso.org/standard/71691.html) specification. | +| 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. | diff --git a/docs/includes/word/packages-and-document-parts.md b/docs/includes/word/packages-and-document-parts.md index a2a0356b..4c1dbf9b 100644 --- a/docs/includes/word/packages-and-document-parts.md +++ b/docs/includes/word/packages-and-document-parts.md @@ -1,7 +1,7 @@ ## Packages and Document Parts An Open XML document is stored as a package, whose format is defined by -[ISO/IEC 29500-2](https://www.iso.org/standard/71691.html). The +[!include[ISO/IEC 29500 URL](../iso-iec-29500-link.md)]. The package can have multiple parts with relationships between them. The relationship between parts controls the category of the document. A document can be defined as a word-processing document if its diff --git a/docs/includes/word/structure.md b/docs/includes/word/structure.md index 0254f652..f6dbc699 100644 --- a/docs/includes/word/structure.md +++ b/docs/includes/word/structure.md @@ -3,7 +3,7 @@ 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](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.aspx) 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 [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. | WordprocessingML Element | Open XML SDK Class | Description | |---|---|---| -| document | [Document](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.document.aspx) | The root element for the main document part. | -| body | [Body](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.body.aspx) | The container for the block level structures such as paragraphs, tables, annotations and others specified in the [ISO/IEC 29500](https://www.iso.org/standard/71691.html) specification. | -| p | [Paragraph](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.paragraph.aspx) | A paragraph. | -| r | [Run](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.run.aspx) | A run. | -| t | [Text](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.text.aspx) | A range of text. | +| 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. | 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/open-xml-sdk.md b/docs/open-xml-sdk.md index aa3a67de..c6e28acd 100644 --- a/docs/open-xml-sdk.md +++ b/docs/open-xml-sdk.md @@ -29,7 +29,7 @@ API and provides strongly-typed classes to manipulate documents that adhere to the Office Open XML File Formats specification. The Office Open XML File Formats specification is an open, international, [ECMA-376, 5th Edition](https://www.ecma-international.org/publications-and-standards/standards/ecma-376/) -and [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +and [!include[ISO/IEC 29500 URL](./includes/iso-iec-29500-link.md)] standard. The Open XML file formats are useful for developers because they are an open standard and are based on well-known technologies: ZIP and XML. @@ -40,7 +40,7 @@ The Open XML SDK encapsulates many common tasks that developers perform on Open XML packages, so that you can perform complex operations with just a few lines of code. -Portions of ISO/IEC 29500:20081 are referenced in the SDK. +Portions of [!include[ISO/IEC 29500 version](./includes/iso-iec-29500-version.md)]1 are referenced in the SDK. [!include[Add-ins note](./includes/addinsnote.md)] @@ -65,8 +65,8 @@ Portions of ISO/IEC 29500:20081 are referenced in the SDK. - [Open XML SDK for Microsoft Office](https://www.nuget.org/packages/DocumentFormat.OpenXml) - [Microsoft Office Developer Center](https://developer.microsoft.com/office/docs) - [Samples on GitHub](https://github.com/OfficeDev) -- [Open XML SDK copyright notice](https://msdn.microsoft.com/library/6165f4ad-2e4d-4852-921a-087782af364d(Office.15).aspx) +- [Open XML SDK copyright notice](/previous-versions/office/bb509417(v=office.15)) - [Accessibility features in the Microsoft Office System](https://www.microsoft.com/accessibility/) -- [Document conventions in Office Developer documentation](https://msdn.microsoft.com/office/aa905365.aspx) +- [Document conventions in Office Developer documentation](/previous-versions/office/dn602610(v=office.15)) -1© ISO/IEC2900:2008. This material is reproduced from ISO/IEC 29500:2008 with permission of the American National Standards Institute (ANSI) on behalf of ISO. +1© [!include[ISO/IEC 29500 version](./includes/iso-iec-29500-version.md)]. This material is reproduced from [!include[ISO/IEC 29500 version](./includes/iso-iec-29500-version.md)] with permission of the American National Standards Institute (ANSI) on behalf of ISO. 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 b5b6e2a2..2182b0ad 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](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.presentationdocument.aspx) class represents a +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)](https://msdn.microsoft.com/library/office/cc562287.aspx) method that uses a +[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 access, specify the value **false** for this parameter. @@ -65,7 +65,7 @@ object that is created or named in the **using** statement, in this case **theme ----------------------------------------------------------------------------- ## Structure of the Theme Element -The following information from the [ISO/IEC 29500](https://www.iso.org/standard/71691.html) specification can +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. > This element defines the root level complex type associated with a @@ -83,7 +83,7 @@ be useful when working with this element. > backgrounds, fills, and effects for different objects in a > presentation. *end example*] > -> © ISO/IEC29500: 2008. +> © [!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 c6dd62ac..8d0cb092 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 @@ -67,7 +67,7 @@ The basic document structure of a PresentationML document consists of a number of parts, among which is the Shape Tree (**sp Tree**) element. -The following text from the [ISO/IEC 29500](https://www.iso.org/standard/71691.html) specification +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. > This element specifies all shapes within a slide. Contained within @@ -102,7 +102,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*] > -> © ISO/IEC29500: 2008. +> © [!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. 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 5f76541e..a825670c 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 @@ -30,28 +30,28 @@ 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](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.presentationdocument.aspx) class. The +is represented in the Open XML SDK by the [PresentationDocument](/dotnet/api/documentformat.openxml.packaging.presentationdocument) class. The presentation document contains, among other parts, a presentation part. -The presentation part, represented in the Open XML SDK by the [PresentationPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.presentationpart.aspx) class, contains the basic +The presentation part, represented in the Open XML SDK by the [PresentationPart](/dotnet/api/documentformat.openxml.packaging.presentationpart) 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 \. 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)](https://msdn.microsoft.com/library/office/cc535977.aspx) -method of the [PresentationDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.presentationdocument.aspx) class, as shown here +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 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 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](https://msdn.microsoft.com/library/office/documentformat.openxml.presentationdocumenttype.aspx) enumerated value. +defined by a [PresentationDocumentType](/dotnet/api/documentformat.openxml.presentationdocumenttype) enumerated value. -Next, the code calls [AddPresentationPart()](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.presentationdocument.addpresentationpart.aspx), which creates and +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](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.presentationpart.presentation.aspx) property equal to the instance -of the [Presentation](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.presentation.aspx) class returned from a call to +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. In order to create a complete, useable, and valid presentation, the code @@ -79,20 +79,20 @@ slide layout, slide master, and theme parts. 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](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.aspx) +PresentationML elements. You can find these classes in the [DocumentFormat.OpenXml.Presentation](/dotnet/api/documentformat.openxml.presentation) 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](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.aspx) namespace. +actually part of the [DocumentFormat.OpenXml.Drawing](/dotnet/api/documentformat.openxml.drawing) namespace. Themes are common to all Open XML markup languages. | PresentationML Element | Open XML SDK Class | |---|---| -| <presentation> | [Presentation](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.presentation.aspx) | -| <sld> | [Slide](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.slide.aspx) | -| <sldMaster> | [SlideMaster](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.slidemaster.aspx) | -| <sldLayout> | [SlideLayout](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.slidelayout.aspx) | -| <theme> | [Theme](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.theme.aspx) | +| <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 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 c03d56a5..f27d74ca 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 @@ -32,7 +32,7 @@ slides, and the second is deleting a slide at a specific index. -------------------------------------------------------------------------------- ## Getting a Presentation Object -In the Open XML SDK, the **[PresentationDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.presentationdocument.aspx)** 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)](https://msdn.microsoft.com/library/office/cc562287.aspx)** 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. +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 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 index 038d5b45..83f73734 100644 --- 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 @@ -24,11 +24,11 @@ presentation programmatically. ## Getting a PresentationDocument Object -In the Open XML SDK, the [PresentationDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.presentationdocument.aspx) class represents a +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)](https://msdn.microsoft.com/library/office/cc562287.aspx) method that uses a +[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 @@ -70,7 +70,7 @@ object that is created or named in the **using** statement, in this case *doc*. ## The Structure of the Comment Element -The following text from the [ISO/IEC 29500](https://www.iso.org/standard/71691.html) specification +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 @@ -82,7 +82,7 @@ introduces comments in a presentation package. > displaying application decides when to display comments and determines > their visual appearance. > -> © ISO/IEC29500: 2008. +> © [!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 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 097d24a4..d7ba13a1 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 @@ -24,11 +24,11 @@ programmatically. -------------------------------------------------------------------------------- ## Getting a PresentationDocument Object -In the Open XML SDK, the [PresentationDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.presentationdocument.aspx) class represents a +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 -[PresentationDocument.Open(String, Boolean)](https://msdn.microsoft.com/library/office/cc562287.aspx) +[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 @@ -74,8 +74,7 @@ object that is created or named in the **using** statement, in this case **docum ## Structure of the Hyperlink Element 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 [ISO/IEC -29500](https://www.iso.org/standard/71691.html) specification +hyperlink element. The following text from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the **id** (Hyperlink Target). > Specifies the ID of the relationship whose target shall be used as the @@ -118,7 +117,7 @@ introduces the **id** (Hyperlink Target). > The possible values for this attribute are defined by the > ST\_RelationshipId simple type(§22.8.2.1). > -> © ISO/IEC29500: 2008. +> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] -------------------------------------------------------------------------------- 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 bc2893bc..083855d4 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 @@ -24,11 +24,11 @@ programmatically. -------------------------------------------------------------------------------- ## Getting a PresentationDocument object -In the Open XML SDK, the [PresentationDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.presentationdocument.aspx) class represents a +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 -[PresentationDocument.Open(String, Boolean)](https://msdn.microsoft.com/library/office/cc562287.aspx) +[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 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 e9131cea..1c03a39c 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 @@ -24,11 +24,11 @@ all of the text in all of the slides in a presentation programmatically. -------------------------------------------------------------------------------- ## Getting a PresentationDocument object -In the Open XML SDK, the [PresentationDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.presentationdocument.aspx) class represents a +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 -[PresentationDocument.Open(String, Boolean)](https://msdn.microsoft.com/library/office/cc562287.aspx) +[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 @@ -121,4 +121,4 @@ The following is the complete sample code in both C\# and Visual Basic. [Open XML SDK class library -reference](https://msdn.microsoft.com/library/36c8a76e-ce1b-5959-7e85-5d77db7f46d6(Office.15).aspx) +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 fcad0560..f06c1b30 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 @@ -25,11 +25,11 @@ programmatically. --------------------------------------------------------------------------------- ## Getting a PresentationDocument Object -In the Open XML SDK, the **[PresentationDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.presentationdocument.aspx)** class represents a +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 -**[PresentationDocument.Open(String, Boolean)](https://msdn.microsoft.com/library/office/cc562287.aspx)** +**[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 @@ -105,4 +105,4 @@ Following is the complete sample code in both C\# and Visual Basic. [Open XML SDK class library -reference](https://msdn.microsoft.com/library/36c8a76e-ce1b-5959-7e85-5d77db7f46d6(Office.15).aspx) +reference](/office/open-xml/open-xml-sdk) 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 04dc8770..1c0c65f2 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 @@ -23,10 +23,10 @@ insert a new slide into a presentation programmatically. ## Getting a PresentationDocument Object -In the Open XML SDK, the [PresentationDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.presentationdocument.aspx) class represents a +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)](https://msdn.microsoft.com/library/office/cc562287.aspx) method that uses a +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 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 05214688..e800cebe 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 @@ -24,11 +24,11 @@ programmatically. ## Getting a PresentationDocument Object -In the Open XML SDK, the [PresentationDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.presentationdocument.aspx) class represents a +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)](https://msdn.microsoft.com/library/office/cc562287.aspx) method that uses a +[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 @@ -64,7 +64,7 @@ object that is created or named in the **using** statement, in this case *doc*. ## Structure of the Shape Text Body -The following text from the [ISO/IEC 29500](https://www.iso.org/standard/71691.html) specification +The following text from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the structure of this element. > This element specifies the existence of text to be contained within @@ -72,7 +72,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. > -> © ISO/IEC29500: 2008. +> © [!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. 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 142b1f0e..e8bf6e84 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 @@ -24,11 +24,11 @@ programmatically. -------------------------------------------------------------------------------- ## Getting a Presentation Object -In the Open XML SDK, the [PresentationDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.presentationdocument.aspx) class represents a +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)](https://msdn.microsoft.com/library/office/cc562287.aspx) method that uses a +[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. In order to count the number of slides in a presentation, it is best to open the file for read-only access in 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 c704cde9..cf9211df 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 @@ -35,20 +35,20 @@ document. ## Create an Instance of the PresentationDocument Class -In the Open XML SDK, the [PresentationDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.presentationdocument.aspx) class represents a +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](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.presentationdocument.open.aspx) methods. Several Open methods are +of the [Open](/dotnet/api/documentformat.openxml.packaging.presentationdocument.open) methods. Several Open methods are provided, each with a different signature. The following table contains a subset of the overloads for the **Open** method that you can use to open the package. | Name | Description | |---|---| -| [Open(String, Boolean)](https://msdn.microsoft.com/library/office/cc562287.aspx) | Create a new instance of the **PresentationDocument** class from the specified file. | -| [Open(Stream, Boolean)](https://msdn.microsoft.com/library/office/cc536282.aspx) | Create a new instance of the **PresentationDocument** class from the I/O stream. | -| [Open(Package)](https://msdn.microsoft.com/library/office/cc514901.aspx) | Create a new instance of the **PresentationDocument** class from the specified package. | +| [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. | The previous table includes two **Open** @@ -57,7 +57,7 @@ whether a document is editable. To open a document for read-only access, specify the value **false** for this parameter. For example, you can open the presentation file as read-only and assign -it to a [PresentationDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.presentationdocument.aspx) object as shown in the +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 that represents the path of the file from which you want to open the 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 2afaeeff..1808f843 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 @@ -81,8 +81,8 @@ values, as shown in the following code. ## 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](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.presentationdocument.open.aspx) 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](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.presentationdocument.presentationpart.aspx) 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 [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**. ### [C#](#tab/cs-2) ```csharp @@ -113,7 +113,7 @@ final **false** parameter value). Given the open presentation, the code uses the ## 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](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.presentationpart.slideparts.aspx) 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. +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 @@ -144,14 +144,14 @@ If the presentation part reference is not null (and it will not be, for any vali 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](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.slide.show.aspx) property that contains a value, and +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 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 if you had hidden and then unhidden the slide. The following code -uses the [Where](https://msdn2.microsoft.com/library/bb301979)** +uses the [Where](/dotnet/api/system.linq.enumerable.where)** function with a lambda expression to do the work. ### [C#](#tab/cs-4) diff --git a/docs/presentation/structure-of-a-presentationml-document.md b/docs/presentation/structure-of-a-presentationml-document.md index 676c0160..760a57a8 100644 --- a/docs/presentation/structure-of-a-presentationml-document.md +++ b/docs/presentation/structure-of-a-presentationml-document.md @@ -41,7 +41,7 @@ Using the Open XML SDK, you can create document structure and content that uses | 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 [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) specification, © ISO/IEC29500: 2008. +*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 @@ -51,7 +51,7 @@ A PresentationML package's main part starts with a \ root element The root element of the Presentation Properties part is the \ element. -The [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) specification describes the Open XML PresentationML Presentation Properties part as follows: +The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML Presentation Properties part as follows: An instance of this part type contains all the presentation's properties. @@ -81,13 +81,13 @@ 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. -© ISO/IEC29500: 2008. +© [!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 [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) specification describes the Open XML PresentationML Slide Master part as follows: +The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML Slide Master part as follows: An instance of this part type contains the master definition of formatting, text, and objects that appear on each slide in the presentation that is derived from this slide master. @@ -141,13 +141,13 @@ 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. -© ISO/IEC29500: 2008. +© [!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 [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) specification describes the Open XML PresentationML Slide Layout part as follows: +The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML Slide Layout part as follows: An instance of this part type contains the definition for a slide layout template for this presentation. This template defines the default appearance and positioning of drawing objects on this slide type when it is created. @@ -207,7 +207,7 @@ 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. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### Slide Part @@ -215,7 +215,7 @@ 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. -The [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) specification describes the Open XML PresentationML Slide part as follows: +The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML Slide part as follows: A Slide part contains the contents of a single slide. @@ -285,13 +285,13 @@ 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. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### Theme Part The root element of the Theme part is the \ element. -The [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) specification describes the Open XML DrawingML Theme part as follows: +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. @@ -335,13 +335,13 @@ 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. -© ISO/IEC29500: 2008. +© [!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 [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) specification describes the Open XML PresentationML Notes Master part as follows: +The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML Notes Master part as follows: An instance of this part type contains information about the content and formatting of all notes pages. @@ -393,13 +393,13 @@ 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. -© ISO/IEC29500: 2008. +© [!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 [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) specification describes the Open XML PresentationML Notes Slide part as follows: +The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML Notes Slide part as follows: An instance of this part type contains the notes for a single slide. @@ -454,13 +454,13 @@ 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. -© ISO/IEC29500: 2008. +© [!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 [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) specification describes the Open XML PresentationML Handout Master part as follows: +The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML Handout Master part as follows: An instance of this part type contains the look, position, and size of the slides, notes, header and footer text, date, or page number on the presentation's handout. @@ -513,13 +513,13 @@ 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. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### Comments Part The root element of the Comments part is the \ element. -The [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) specification describes the Open XML PresentationML Comments part as +The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML Comments part as follows: An instance of this part type contains the comments for a single slide. Each comment is tied to its author via an author-ID. Each comment's index number and author-ID combination are unique. @@ -561,14 +561,14 @@ 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. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### Comments Author Part The root element of the Comments Author part is the \ element. -The [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) specification describes the Open XML PresentationML Comments Author part as follows: +The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML Comments Author part as follows: An instance of this part type contains information about each author who has added a comment to the document. That information includes the author's name, initials, a unique author-ID, a last-comment-index-used count, and a display color. (The color can be used when displaying comments to distinguish comments from different authors.) @@ -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. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ## The Structure of a Minimum Presentation File @@ -626,16 +626,16 @@ The following XML code is the PresentationML that represents the presentation pa ```xml - + + xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" /> + xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" /> - + @@ -677,7 +677,7 @@ The following XML code is the PresentationML that represents the slide part of t - + @@ -685,7 +685,7 @@ The following XML code is the PresentationML that represents the slide part of t name="Title 1" /> + xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" /> @@ -693,9 +693,9 @@ The following XML code is the PresentationML that represents the slide part of t - - - + + + @@ -703,7 +703,7 @@ The following XML code is the PresentationML that represents the slide part of t - + ``` diff --git a/docs/presentation/working-with-animation.md b/docs/presentation/working-with-animation.md index 4a526887..8f9d298c 100644 --- a/docs/presentation/working-with-animation.md +++ b/docs/presentation/working-with-animation.md @@ -21,7 +21,7 @@ This topic discusses the Open XML SDK for Office **Animate** class and how it re ## Animation in PresentationML -The [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) specification describes the Animation section of the Open XML PresentationML framework as follows: +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: @@ -34,7 +34,7 @@ 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 [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) 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: @@ -63,7 +63,7 @@ The following table lists the child elements of the \ element used when w | \ | CommonBehavior | | \ | TimeAnimateValueList | -The following table from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) 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** | |:---------------|:-----------------------------------------------------------------| @@ -82,7 +82,7 @@ Classes that represent child elements of the \ element and that are there ### CommonBehavior Class -The **CommonBehavior** class corresponds to the \ element. The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) 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. @@ -108,7 +108,7 @@ 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 [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) 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. diff --git a/docs/presentation/working-with-comments.md b/docs/presentation/working-with-comments.md index 982dee9e..c436fcb2 100644 --- a/docs/presentation/working-with-comments.md +++ b/docs/presentation/working-with-comments.md @@ -16,13 +16,13 @@ ms.localizationpriority: medium --- # Working with comments -This topic discusses the Open XML SDK for Office [Comment](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.comment.aspx) class and how it relates to the +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). ## Comments in PresentationML -The [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) specification describes the Comments section of the Open XML PresentationML framework as follows: +The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Comments section of the Open XML PresentationML framework as follows: 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 @@ -33,7 +33,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 [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) 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 @@ -52,11 +52,11 @@ The following table lists the child elements of the \ element used when wo | **PresentationML Element** | **Open XML SDK Class** | |----------------------------|------------------------------------------------------------------------------------------------------------------------------------------| -| \ | [ExtensionListWithModification](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.extensionlistwithmodification.aspx) | -| \ | [Position](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.position.aspx) | -| \ | [Text](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.text.aspx) | +| \ | [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 [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +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,7 +75,7 @@ therefore commonly associated with the **Comment** class are shown in the follow ### ExtensionListWithModification Class -The **ExtensionListWithModification** class corresponds to the \element. The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +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. @@ -86,7 +86,7 @@ This element specifies the extension list with modification ability within which ### Position Class The **Position** class corresponds to the -\element. The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +\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 @@ -110,7 +110,7 @@ application chooses to display comments. end note] ### Text class The **Text** class corresponds to the -\element. The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +\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 @@ -132,17 +132,17 @@ 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](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.slidecommentspart.aspx) class, which represents a +instance of the [SlideCommentsPart](/dotnet/api/documentformat.openxml.packaging.slidecommentspart) 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](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.commentauthor.aspx) class, which is in turn +instance of the [CommentAuthor](/dotnet/api/documentformat.openxml.presentation.commentauthor) class, which is in turn associated with a similarly named presentation part, represented by the -[CommentAuthorsPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.commentauthorspart.aspx) class. Comment authors +[CommentAuthorsPart](/dotnet/api/documentformat.openxml.packaging.commentauthorspart) class. Comment authors for a presentation are specified in a comment author list, represented -by the [CommentAuthorList](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.commentauthorlist.aspx) class, while comments for +by the [CommentAuthorList](/dotnet/api/documentformat.openxml.presentation.commentauthorlist) class, while comments for each slide are listed in a comments list for that slide, represented by -the [CommentList](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.commentlist.aspx) class. +the [CommentList](/dotnet/api/documentformat.openxml.presentation.commentlist) 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. @@ -245,7 +245,7 @@ or comment authors before the code was run. ```xml - + - + diff --git a/docs/presentation/working-with-handout-master-slides.md b/docs/presentation/working-with-handout-master-slides.md index fdca2df5..cf068982 100644 --- a/docs/presentation/working-with-handout-master-slides.md +++ b/docs/presentation/working-with-handout-master-slides.md @@ -16,10 +16,10 @@ ms.localizationpriority: medium --- # Working with handout master slides -This topic discusses the Open XML SDK for Office [HandoutMaster](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.handoutmaster.aspx) 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 [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). ## Handout Master Slides in PresentationML -The [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) 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,7 +30,7 @@ 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. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] The following table lists the child elements of the \ element used when working with handout master slides and the Open XML @@ -39,10 +39,10 @@ SDK classes that correspond to them. | **PresentationML Element** | **Open XML SDK Class** | |----------------------------|--------------------------------------------------------------------------------------------------------------------------------------------| -| \ | [ColorMap](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.colormap.aspx) | -| \ | [CommonSlideData](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.commonslidedata.aspx) | -| \ | [ExtensionListWithModification](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.extensionlistwithmodification.aspx) | -| \ | [HeaderFooter](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.headerfooter.aspx) | +| \ | [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) | ## Open XML SDK HandoutMaster Class @@ -52,7 +52,7 @@ Classes commonly associated with the **HandoutMaster** class are shown in the fo ### ColorMap Class -The **ColorMap** class corresponds to the \ element. The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) 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 @@ -72,7 +72,7 @@ accent6="accent6" hlink="hlink" folHlink="folHlink"/> ### CommonSlideData Class The **CommonSlideData** class corresponds to -the \ element. The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +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 @@ -90,7 +90,7 @@ slides. The **ExtensionListWithModification** class corresponds to the \element. The following information from the -[ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +[!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the \ element: This element specifies the extension list with modification ability @@ -107,7 +107,7 @@ store whether this extension property has been modified. ### HeaderFooter Class The **HeaderFooter** class corresponds to the -\ element. The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +\ 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. @@ -120,7 +120,7 @@ slide numbering, and custom header and footer text. 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](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.handoutmasterpart.aspx) class, which represents a +an instance of the [HandoutMasterPart](/dotnet/api/documentformat.openxml.packaging.handoutmasterpart) 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. @@ -129,7 +129,7 @@ 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](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.shapetree.aspx) class, and the [Shape](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.shape.aspx) class. +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. ## Open XML SDK Code Example @@ -138,12 +138,12 @@ presentation and creates an instance of an Open XML SDK**HandoutMaster** class i 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](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.shapetree.aspx) class, whose constructor, in -turn, creates additional class instances: an instance of the [NonVisualGroupShapeProperties](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.nonvisualgroupshapeproperties.aspx) class, an -instance of the [GroupShapeProperties](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.groupshapeproperties.aspx) class, and an instance -of the [Shape](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.shape.aspx) class. +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](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.aspx) +The namespace represented by the letter *P* in the code is the [DocumentFormat.OpenXml.Presentation](/dotnet/api/documentformat.openxml.presentation) namespace. ### [C#](#tab/cs) @@ -158,7 +158,7 @@ the PresentationML document referenced in the code. ```xml - + @@ -168,7 +168,7 @@ the PresentationML document referenced in the code. - + @@ -176,7 +176,7 @@ the PresentationML document referenced in the code. name="Title 1" /> + xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" /> @@ -184,9 +184,9 @@ the PresentationML document referenced in the code. - - - + + + diff --git a/docs/presentation/working-with-notes-slides.md b/docs/presentation/working-with-notes-slides.md index 1118f431..1b7dfbd1 100644 --- a/docs/presentation/working-with-notes-slides.md +++ b/docs/presentation/working-with-notes-slides.md @@ -16,13 +16,13 @@ ms.localizationpriority: medium --- # Working with notes slides -This topic discusses the Open XML SDK for Office [NotesSlide](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.notesslide.aspx) class and how it relates to the +This topic discusses the Open XML SDK for Office [NotesSlide](/dotnet/api/documentformat.openxml.presentation.notesslide) class and how it relates to the Open XML File Format PresentationML schema. -------------------------------------------------------------------------------- ## Notes Slides in PresentationML -The [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML \ element used to represent notes slides in a PresentationML document as follows: @@ -47,7 +47,7 @@ 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. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] The \ element is the root element of the PresentationML Notes Slide part. For more information about the overall structure of the @@ -61,11 +61,11 @@ that correspond to them. | **PresentationML Element** | **Open XML SDK Class** | |----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------| -| \ | [ColorMapOverride](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.colormapoverride.aspx) | -| \ | [CommonSlideData](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.commonslidedata.aspx) | -| \ | [ExtensionListWithModification](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.extensionlistwithmodification.aspx) | +| \ | [ColorMapOverride](/dotnet/api/documentformat.openxml.presentation.colormapoverride) | +| \ | [CommonSlideData](/dotnet/api/documentformat.openxml.presentation.commonslidedata) | +| \ | [ExtensionListWithModification](/dotnet/api/documentformat.openxml.presentation.extensionlistwithmodification) | -The following table from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +The following table from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the attributes of the \ element. @@ -74,7 +74,7 @@ specification describes the attributes of the \ element. | 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. | -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] --------------------------------------------------------------------------------- @@ -90,7 +90,7 @@ are therefore commonly associated with the **NotesSlide** class are shown in the ### ColorMapOverride Class The **ColorMapOverride** class corresponds to -the \ element. The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +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 @@ -100,12 +100,12 @@ 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. -© ISO/IEC29500: 2008. +© [!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 [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +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 @@ -119,13 +119,13 @@ The actual data in \ describe only the particular parent slide; it is only the type of information stored that is common across all slides. -© ISO/IEC29500: 2008. +© [!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 -[ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +[!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the \ element: This element specifies the extension list with modification ability @@ -138,26 +138,26 @@ framework. [Note: Using this extLst element allows the generating application to store whether this extension property has been modified. end note] -© ISO/IEC29500: 2008. +© [!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](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.notesslidepart.aspx) class, which represents a +instance of the [NotesSlidePart](/dotnet/api/documentformat.openxml.packaging.notesslidepart) 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](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.notesmaster.aspx) class, which in turn is +instance may also be associated with an instance of the [NotesMaster](/dotnet/api/documentformat.openxml.presentation.notesmaster) class, which in turn is associated with a similarly named presentation part, represented by the -[NotesMasterPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.notesmasterpart.aspx) class. +[NotesMasterPart](/dotnet/api/documentformat.openxml.packaging.notesmasterpart) 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. Among these classes, as shown in the following code sample, are the -**CommonSlideData** class and the **ColorMapOverride** class. The [ShapeTree](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.shapetree.aspx) class and the [Shape](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.shape.aspx) classes are in turn associated with +**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. @@ -168,12 +168,12 @@ presentation and creates an instance of an Open XML SDK**NotesSlide** class in t **NotesSlide** class constructor creates instances of the **CommonSlideData** class and the **ColorMap** class. The **CommonSlideData** class constructor creates an -instance of the [ShapeTree](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.shapetree.aspx) class, whose constructor in turn -creates additional class instances: an instance of the [NonVisualGroupShapeProperties](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.nonvisualgroupshapeproperties.aspx) class, an -instance of the [GroupShapeProperties](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.groupshapeproperties.aspx) class, and an instance -of the [Shape](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.shape.aspx) class. +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](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.aspx) +The namespace represented by the letter *P* in the code is the [DocumentFormat.OpenXml.Presentation](/dotnet/api/documentformat.openxml.presentation) namespace. ### [C#](#tab/cs) @@ -189,7 +189,7 @@ the PresentationML document referenced in the code. ```xml - + @@ -199,7 +199,7 @@ the PresentationML document referenced in the code. - + @@ -207,7 +207,7 @@ the PresentationML document referenced in the code. name="" /> + xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" /> @@ -215,9 +215,9 @@ the PresentationML document referenced in the code. - - - + + + @@ -225,7 +225,7 @@ the PresentationML document referenced in the code. - + ``` diff --git a/docs/presentation/working-with-presentation-slides.md b/docs/presentation/working-with-presentation-slides.md index 7ce19fef..1275b7b7 100644 --- a/docs/presentation/working-with-presentation-slides.md +++ b/docs/presentation/working-with-presentation-slides.md @@ -16,7 +16,7 @@ ms.localizationpriority: high --- # Working with presentation slides -This topic discusses the Open XML SDK for Office [Slide](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.slide.aspx) class and how it relates to the Open +This topic discusses the Open XML SDK for Office [Slide](/dotnet/api/documentformat.openxml.presentation.slide) 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 @@ -25,7 +25,7 @@ PresentationML document](structure-of-a-presentationml-document.md)**. --------------------------------------------------------------------------------- ## Presentation Slides in PresentationML -The [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML \ element used to represent a presentation slide in a PresentationML document as follows: @@ -52,7 +52,7 @@ In the above example the order specified to present the slides is slide 4, then 3, 2, and finally 5. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] The \ element is the root element of the PresentationML Slide part. For more information about the overall structure of the parts and @@ -65,11 +65,11 @@ that correspond to them. | **PresentationML Element** | **Open XML SDK Class** | |----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------| -| \ | [ColorMapOverride](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.colormapoverride.aspx) | -| \ | [CommonSlideData](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.commonslidedata.aspx) | -| \ | [ExtensionListWithModification](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.extensionlistwithmodification.aspx) | -| \ | [Timing](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.timing.aspx) | -| \ | [Transition](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.transition.aspx) | +| \ | [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 @@ -84,7 +84,7 @@ class are shown in the following sections. ### ColorMapOverride Class The **ColorMapOverride** class corresponds to -the \ element. The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +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 @@ -94,12 +94,12 @@ 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. -© ISO/IEC29500: 2008. +© [!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 [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +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 @@ -113,13 +113,13 @@ The actual data in \ describe only the particular parent slide; it is only the type of information stored that is common across all slides. -© ISO/IEC29500: 2008. +© [!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 -[ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +[!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the \ element: This element specifies the extension list with modification ability @@ -132,12 +132,12 @@ framework. [Note: Using this extLst element allows the generating application to store whether this extension property has been modified. end note] -© ISO/IEC29500: 2008. +© [!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 [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +\ 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 @@ -147,12 +147,12 @@ 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. -© ISO/IEC29500: 2008. +© [!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 [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +\ 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 @@ -160,24 +160,24 @@ 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. -© ISO/IEC29500: 2008. +© [!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](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.slidepart.aspx) class, which represents a slide +instance of the [SlidePart](/dotnet/api/documentformat.openxml.packaging.slidepart) 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](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.slidelayout.aspx) and [SlideMaster](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.slidemaster.aspx) classes, which are in turn +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 associated with similarly named required presentation parts, represented -by the [SlideLayoutPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.slidelayoutpart.aspx) and [SlideMasterPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.slidemasterpart.aspx) classes. +by the [SlideLayoutPart](/dotnet/api/documentformat.openxml.packaging.slidelayoutpart) and [SlideMasterPart](/dotnet/api/documentformat.openxml.packaging.slidemasterpart) 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](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.shapetree.aspx) class, and the [Shape](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.shape.aspx) class. +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. -------------------------------------------------------------------------------- @@ -189,13 +189,13 @@ 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](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.nonvisualgroupshapeproperties.aspx) class, the [GroupShapeProperties](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.groupshapeproperties.aspx) class, and the **Shape** class. +the [NonVisualGroupShapeProperties](/dotnet/api/documentformat.openxml.presentation.nonvisualgroupshapeproperties) class, the [GroupShapeProperties](/dotnet/api/documentformat.openxml.presentation.groupshapeproperties) 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 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](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.aspx) +The namespace represented by the letter *P* in the code is the [DocumentFormat.OpenXml.Presentation](/dotnet/api/documentformat.openxml.presentation) namespace. ### [C#](#tab/cs-0) @@ -289,7 +289,7 @@ is written to the PresentationML document file referenced in the code. ```xml - + @@ -298,13 +298,13 @@ is written to the PresentationML document file referenced in the code. - + - + @@ -312,9 +312,9 @@ is written to the PresentationML document file referenced in the code. - - - + + + @@ -322,7 +322,7 @@ is written to the PresentationML document file referenced in the code. - + ``` diff --git a/docs/presentation/working-with-presentations.md b/docs/presentation/working-with-presentations.md index 6cd68f78..2f0708a6 100644 --- a/docs/presentation/working-with-presentations.md +++ b/docs/presentation/working-with-presentations.md @@ -16,7 +16,7 @@ ms.localizationpriority: medium --- # Working with presentations -This topic discusses the Open XML SDK for Office [Presentation](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.presentation.aspx) class and how it relates to +This topic discusses the Open XML SDK for Office [Presentation](/dotnet/api/documentformat.openxml.presentation.presentation) 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 @@ -25,7 +25,7 @@ PresentationML document](structure-of-a-presentationml-document.md). --------------------------------------------------------------------------------- ## Presentations in PresentationML -The [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML \ element used to represent a presentation in a PresentationML document as follows: @@ -55,7 +55,7 @@ size and default text styles.
``` -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] The \ element typically contains child elements that list slide masters, slides, and custom slide shows contained within the @@ -75,16 +75,16 @@ Open XML SDK classes that correspond to them. | **PresentationML Element** | **Open XML SDK Class** | |----------------------------|-------------------------------------------------------------------------------------------------------------------------------------| -| \ | [SlideMasterIdList](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.slidemasteridlist.aspx) | -| \ | [SlideMasterId](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.slidemasterid.aspx) | -| \ | [SlideIdList](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.slideidlist.aspx) | -| \ | [SlideId](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.slideid.aspx) | -| \ | [NotesMasterIdList](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.notesmasteridlist.aspx) | -| \ | [HandoutMasterIdList](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.handoutmasteridlist.aspx) | -| \ | [CustomShowList](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.customshowlist.aspx) | -| \ | [SlideSize](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.slidesize.aspx) | -| \ | [NotesSize](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.notessize.aspx) | -| \ | [DefaultTextStyle](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.defaulttextstyle.aspx) | +| \ | [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 @@ -100,7 +100,7 @@ sections. All slides that share the same master inherit the same layout from that master. The **SlideMasterIdList** class -corresponds to the \ element. The [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +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,12 +110,12 @@ 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. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### SlideMasterId Class The **SlideMasterId** class corresponds to the -\ element. The [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +\ 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,12 +139,12 @@ embedTrueTypeFonts="1">
``` -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### SlideIdList Class The **SlideIdList** class corresponds to the -\ element. The [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +\ 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,12 +154,12 @@ 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. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### SlideId Class The **SlideId** class corresponds to the -\ element. The [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +\ 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: @@ -186,12 +186,12 @@ embedTrueTypeFonts="1"> ``` -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### NotesMasterIdList Class The **NotesMasterIdList** class corresponds to -the \ element. The [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +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,12 +201,12 @@ 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. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### HandoutMasterIdList Class The **HandoutMasterIdList** class corresponds -to the \ element. The [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +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 list in a PresentationML document as follows: @@ -216,12 +216,12 @@ 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. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### CustomShowList Class The **CustomShowList** class corresponds to the -\ element. The [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +\ 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,12 +231,12 @@ 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. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### SlideSize Class The **SlideSize** class corresponds to the -\ element. The [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +\ 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,12 +258,12 @@ embedTrueTypeFonts="1"> ``` -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### NotesSize Class The **NotesSize** class corresponds to the -\ element. The [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +\ 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,12 +288,12 @@ embedTrueTypeFonts="1"> ``` -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### DefaultTextStyle Class The DefaultTextStyle class corresponds to the \ -element. The [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML \ element used to represent default text style in a PresentationML document as follows: @@ -304,14 +304,14 @@ 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. -© ISO/IEC29500: 2008. +© [!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](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.presentationpart.aspx) class, which represents a +with an instance of the [PresentationPart](/dotnet/api/documentformat.openxml.packaging.presentationpart) class, which represents a presentation part, one of the required parts of a PresentationML presentation file package. @@ -325,12 +325,12 @@ code example, are the **SlideMasterIdList**, -------------------------------------------------------------------------------- ## 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)](https://msdn.microsoft.com/library/office/cc535977.aspx) -method of the [PresentationDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.presentationdocument.aspx) 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 [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 SDK to create an instance of that same class that has the specified -name and file path. Then it uses the [AddPresentationPart()](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.presentationdocument.addpresentationpart.aspx) method to add an -instance of the [PresentationPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.presentationpart.aspx) class to the document -file. Next, it creates an instance of the [Presentation](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.presentation.aspx) class that represents the +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 @@ -353,12 +353,12 @@ PresentationML document referenced in the code. ```xml - + - + - + diff --git a/docs/presentation/working-with-slide-layouts.md b/docs/presentation/working-with-slide-layouts.md index bd322378..9f0a062d 100644 --- a/docs/presentation/working-with-slide-layouts.md +++ b/docs/presentation/working-with-slide-layouts.md @@ -17,11 +17,11 @@ ms.localizationpriority: medium # Working with slide layouts -This topic discusses the Open XML SDK for Office [SlideLayout](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.slidelayout.aspx) class and how it relates to the Open XML File Format PresentationML schema. +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. ## Slide Layouts in PresentationML -The [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) 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 @@ -39,14 +39,14 @@ classes that correspond to them. | **PresentationML Element** | **Open XML SDK Class** | |----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------| -| \ | [ColorMapOverride](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.colormapoverride.aspx) | -| \ | [CommonSlideData](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.commonslidedata.aspx) | -| \ | [ExtensionListWithModification](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.extensionlistwithmodification.aspx) | -| \ | [HeaderFooter](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.headerfooter.aspx) | -| \ | [Timing](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.timing.aspx) | -| \ | [Transition](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.transition.aspx) | - -The following table from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +| \ | [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) | + +The following table from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the attributes of the \ element. @@ -73,7 +73,7 @@ list. ### ColorMapOverride Class The **ColorMapOverride** class corresponds to -the \ element. The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +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 @@ -86,7 +86,7 @@ slide, presentation slide, or slide layout. ### CommonSlideData Class The **CommonSlideData** class corresponds to -the \ element. The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +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 @@ -104,7 +104,7 @@ slides. The **ExtensionListWithModification** class corresponds to the \element. The following information from the -[ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +[!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the \ element: This element specifies the extension list with modification ability @@ -120,7 +120,7 @@ framework. ### HeaderFooter Class The **HeaderFooter** class corresponds to the -\ element. The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +\ 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. @@ -131,7 +131,7 @@ slide numbering, and custom header and footer text. ### Timing Class The **Timing** class corresponds to the -\ element. The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +\ 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 @@ -143,7 +143,7 @@ PresentationML framework. ### Transition Class -The **Transition** class corresponds to the \ element. The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) 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. @@ -151,24 +151,24 @@ This element specifies the kind of slide transition that should be used to trans 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](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.slidelayoutpart.aspx) class, which represents a +instance of the [SlideLayoutPart](/dotnet/api/documentformat.openxml.packaging.slidelayoutpart) 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](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.slidemaster.aspx) and [Slide](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.slide.aspx) classes, which are in turn associated +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 with similarly named required presentation parts, represented by the -[SlideMasterPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.slidemasterpart.aspx) and [SlidePart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.slidepart.aspx)classes. +[SlideMasterPart](/dotnet/api/documentformat.openxml.packaging.slidemasterpart) and [SlidePart](/dotnet/api/documentformat.openxml.packaging.slidepart)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 \ element. Among these classes, as shown in the following code sample, are -the **CommonSlideData** class, the **ColorMapOverride** class, the [ShapeTree](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.shapetree.aspx) class, and the [Shape](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.shape.aspx) class. +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. ## 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](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.shapetree.aspx) class, whose constructor in turn creates additional class instances: an instance of the [NonVisualGroupShapeProperties (https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.nonvisualgroupshapeproperties.aspx) class, an instance of the [GroupShapeProperties](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.groupshapeproperties.aspx) class, and an instance of the [Shape](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.shape.aspx) 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 [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 (https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.aspx) namespace. +The namespace represented by the letter *P* in the code is the [DocumentFormat.OpenXml.Presentation (/dotnet/api/documentformat.openxml.presentation) namespace. ### [C#](#tab/cs) [!code-csharp[](../../samples/presentation/working_with_slide_layouts/cs/Program.cs)] @@ -182,7 +182,7 @@ When the Open XML SDK code is run, the following XML is written to the Presentat ```xml - + @@ -192,7 +192,7 @@ When the Open XML SDK code is run, the following XML is written to the Presentat - + @@ -200,7 +200,7 @@ When the Open XML SDK code is run, the following XML is written to the Presentat name="" /> + xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" /> @@ -208,9 +208,9 @@ When the Open XML SDK code is run, the following XML is written to the Presentat - - - + + + @@ -218,7 +218,7 @@ When the Open XML SDK code is run, the following XML is written to the Presentat - + ``` diff --git a/docs/presentation/working-with-slide-masters.md b/docs/presentation/working-with-slide-masters.md index d54e70af..8b624f60 100644 --- a/docs/presentation/working-with-slide-masters.md +++ b/docs/presentation/working-with-slide-masters.md @@ -16,11 +16,11 @@ ms.localizationpriority: medium # Working with slide masters -This topic discusses the Open XML SDK for Office **[SlideMaster](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.slidemaster.aspx)** class and how it relates to the Open XML File Format PresentationML schema. +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. ## Slide Masters in PresentationML -The [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) 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. @@ -30,16 +30,16 @@ The following table lists the child elements of the \ element used w | **PresentationML Element** | **Open XML SDK Class** | |:---------------------------|:---------------------------------------------------------------------------------------------------------------------------| -| \ | [ColorMap](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.colormap.aspx) | -| \ | [CommonSlideData](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.commonslidedata.aspx) | -| \ | [ExtensionListWithModification](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.extensionlistwithmodification.aspx) | -| \ | [HeaderFooter](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.headerfooter.aspx) | -| \ | [SlideLayoutIdList](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.slidelayoutidlist.aspx) | -| \ | [Timing](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.timing.aspx) | -| \ | [Transition](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.transition.aspx) | -| \ | [TextStyles](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.textstyles.aspx) | - -The following table from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +| \ | [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. | **Attributes** | **Description** | @@ -59,13 +59,13 @@ list. ### ColorMapOverride Class -The **ColorMapOverride** class corresponds to the \ element. The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) 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. ### CommonSlideData Class -The **CommonSlideData** class corresponds to the \ element. The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) 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. @@ -73,7 +73,7 @@ The actual data in \ describe only the particular parent slide; it is onl ### ExtensionListWithModification Class -The **ExtensionListWithModification** class corresponds to the \element. The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) 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. @@ -83,31 +83,31 @@ framework. ### HeaderFooter Class -The **HeaderFooter** class corresponds to the \ element. The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) 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 [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) 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 [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) 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. ### Transition Class -The **Transition** class corresponds to the \ element. The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) 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 [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) 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. @@ -138,16 +138,16 @@ 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](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.slidemasterpart.aspx)** 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](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.slidelayout.aspx)** and <**[Slide](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.slide.aspx)** classes, which are in turn associated with similarly named required presentation parts, represented by the **[SlideLayoutPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.slidelayoutpart.aspx)** and **[SlidePart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.slidepart.aspx)** 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 **[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. 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](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.shapetree.aspx)** class, and the **[Shape](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.shape.aspx)** class. +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. ## Open XML SDK Code Example -The following method from the article [How to: Create a presentation document by providing a file name](/office/open-xml/how-to-create-a-presentation-document-by-providing-a-file-name) 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](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.shapetree.aspx)** class, whose constructor in turn creates additional class instances: an instance of the **[NonVisualGroupShapeProperties](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.nonvisualgroupshapeproperties.aspx)** class, an instance of the **[GroupShapeProperties](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.groupshapeproperties.aspx)** class, and an instance of the **[Shape](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.shape.aspx)** 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 **[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 namespace represented by the letter *P* in the code is the **[DocumentFormat.OpenXml.Presentation](https://msdn.microsoft.com/library/office/documentformat.openxml.presentation.aspx)** namespace. +The namespace represented by the letter *P* in the code is the **[DocumentFormat.OpenXml.Presentation](/dotnet/api/documentformat.openxml.presentation)** namespace. ### [C#](#tab/cs) [!code-csharp[](../../samples/presentation/working_with_slide_masters/cs/Program.cs)] @@ -161,7 +161,7 @@ When the Open XML SDK code is run, the following XML is written to the Presentat ```xml - + @@ -171,7 +171,7 @@ When the Open XML SDK code is run, the following XML is written to the Presentat - + @@ -179,7 +179,7 @@ When the Open XML SDK code is run, the following XML is written to the Presentat name="Title Placeholder 1" /> + xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" /> @@ -187,9 +187,9 @@ When the Open XML SDK code is run, the following XML is written to the Presentat - - - + + + @@ -209,7 +209,7 @@ When the Open XML SDK code is run, the following XML is written to the Presentat + xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" /> 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 ec91a417..cc152263 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 @@ -17,14 +17,14 @@ 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 an Microsoft Excel 2010 or Microsoft Excel 2013 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. ## 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](https://msdn.microsoft.com/library/26617206-f4da-416f-a18a-d817b2d4872d(Office.15).aspx) and [Walkthrough: Creating a Custom Tab by Using the Ribbon Designer](https://msdn.microsoft.com/library/312865e6-950f-46ab-88de-fe7eb8036bfe(Office.15).aspx). +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. ### [C#](#tab/cs-xml) @@ -33,7 +33,6 @@ For the purposes of this demonstration, you will need an XML file that contains [!code-vb[](../../samples/spreadsheet/add_custom_ui/vb/Program.vb#snippet4)] *** - ## Create the Macro For this demonstration, the ribbon customization includes a button that attempts to run a macro in the host workbook. To complete the demonstration, you must create a macro in a sample workbook for the button's Click action to call. @@ -86,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](https://msdn.microsoft.com/library/office/documentformat.openxml.office.customui.customui.aspx) 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 [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. ### [C#](#tab/cs-4) [!code-csharp[](../../samples/spreadsheet/add_custom_ui/cs/Program.cs#snippet3)] 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 692a8118..efcdac7d 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 @@ -26,7 +26,7 @@ The sample code starts by passing in to the method **CalculateSumOfCellRange** a 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](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.openxmlpartcontainer.addnewpart.aspx)** method. It inserts the result into the **SharedStringTablePart** object by calling the **InsertSharedStringItem** method. +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. 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. @@ -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](https://msdn2.microsoft.com/library/3zy662f6)** 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 **[Regex.Match](/dotnet/api/system.text.regularexpressions.regex.match)** 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)] @@ -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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sharedstringtable.aspx)** 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 **[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. ### [C#](#tab/cs-5) [!code-csharp[](../../samples/spreadsheet/calculate_the_sum_of_a_range_of_cells/cs/Program.cs#snippet5)] 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 4c2ded5a..69e45658 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 @@ -23,7 +23,7 @@ Office to programmatically create a spreadsheet document. -------------------------------------------------------------------------------- ## Creating a SpreadsheetDocument Object -In the Open XML SDK, the **[SpreadsheetDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.aspx)** class represents an +In the Open XML SDK, the **[SpreadsheetDocument](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument)** class represents an Excel document package. To create an Excel document, create an instance of the **SpreadsheetDocument** class and populate it with parts. At a minimum, the document must have a workbook @@ -31,13 +31,13 @@ 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, call the [Create(Package, SpreadsheetDocumentType)](https://msdn.microsoft.com/library/office/cc562706.aspx) +To create the class instance, call the [Create(Package, SpreadsheetDocumentType)](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.create) 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 path string that represents the document that you want to create. The -second parameter, *type*, is a member of the [SpreadsheetDocumentType](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheetdocumenttype.aspx) enumeration. This +second parameter, *type*, is a member of the [SpreadsheetDocumentType](/dotnet/api/documentformat.openxml.spreadsheetdocumenttype) enumeration. This parameter represents the document type. For example, there are different members of the **SpreadsheetDocumentType** enumeration for add-ins, templates, workbooks, and macro-enabled @@ -58,7 +58,7 @@ method. When you have created the Excel document package, you can add parts to -it. To add the workbook part you call the [AddWorkbookPart()](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.addworkbookpart.aspx) method of the **SpreadsheetDocument** class. +it. To add the workbook part you call the [AddWorkbookPart()](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.addworkbookpart) 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 +67,13 @@ it. To add the workbook part you call the [AddWorkbookPart()](https://msdn.micro *** 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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.workbook.aspx) by passing the **Id**, **SheetId** and **Name** parameters. Use the -[GetIdOfPart(OpenXmlPart)](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.openxmlpartcontainer.getidofpart.aspx) method to get the -**Id** of the **Sheet**. Then add the new sheet to the **Sheet** collection by calling the [Append([])](https://msdn.microsoft.com/library/office/cc801361.aspx) method of the [Sheets](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheets.aspx) class. +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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.workbook.workbookpart.aspx) property of the main document -part, and then add instances of the [WorksheetPart](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.worksheet.worksheetpart.aspx), **Worksheet**, and **Sheet**. The following code example +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 creates a new worksheet, associates the worksheet, and appends the worksheet to the workbook. 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 0b7fdb04..7e864ecb 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 @@ -23,7 +23,7 @@ programmatically. ## How the sample code works -In the following code example, you delete text from a cell in a [SpreadsheetDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.aspx) 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](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.sharedstringtablepart.aspx) object by using the [Remove](https://msdn.microsoft.com/library/office/documentformat.openxml.openxmlelement.remove.aspx) 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 [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. ### [C#](#tab/cs-1) [!code-csharp[](../../samples/spreadsheet/delete_text_from_a_cell/cs/Program.cs#snippet1)] @@ -49,13 +49,13 @@ 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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sharedstringitem.aspx) object, you do not remove +still reference the [SharedStringItem](/dotnet/api/documentformat.openxml.spreadsheet.sharedstringitem) 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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sharedstringtable.aspx) object. +references. Finally, you save the worksheet and the [SharedStringTable](/dotnet/api/documentformat.openxml.spreadsheet.sharedstringtable) object. ### [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 64faf55c..b1b895b7 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 @@ -31,7 +31,7 @@ within the **GetColumnHeading** method. 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](https://msdn.microsoft.com/library/az24scfc.aspx). +cell name. For more information about regular expressions, see [Regular Expression Language Elements](/dotnet/standard/base-types/regular-expression-language-quick-reference). ### [C#](#tab/cs-1) [!code-csharp[](../../samples/spreadsheet/get_a_column_heading/cs/Program.cs#snippet1)] @@ -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](https://msdn.microsoft.com/library/bb291976.aspx) +[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](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.sharedstringtablepart.aspx) object, it gets the +If the content of the cell is stored in the [SharedStringTablePart](/dotnet/api/documentformat.openxml.packaging.sharedstringtablepart) object, it gets the shared string items and returns the content of the column heading using the -[M:System.Int32.Parse(System.String)](https://msdn.microsoft.com/library/b3h1hf19.aspx) -method. If the content of the cell is not in the [SharedStringTable](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sharedstringtable.aspx) object, it returns 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 content of the cell. ### [C#](#tab/cs-5) 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 18197bbd..f1d32132 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 @@ -21,7 +21,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 [ISO/IEC 29500](https://www.iso.org/standard/71691.html) specification +elements. The following text from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces row (\<**row**\>) element. > The row element expresses information about an entire row of a @@ -46,7 +46,7 @@ introduces row (\<**row**\>) element. ``` -> © ISO/IEC29500: 2008. +> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] The following XML Schema code example defines the contents of the row element. @@ -74,7 +74,7 @@ element. ## Cell element -The following text from the [ISO/IEC 29500](https://www.iso.org/standard/71691.html) specification +The following text from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces cell (\<**c**\>) element. > This collection represents a cell in the worksheet. Information about @@ -93,7 +93,7 @@ introduces cell (\<**c**\>) element. ``` -> © ISO/IEC29500: 2008. +> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] The following XML Schema code example defines the contents of this element. @@ -117,7 +117,7 @@ element. ## Cell value element -The following text from the [ISO/IEC 29500](https://www.iso.org/standard/71691.html) specification +The following text from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces Cell Value (\<**c**\>) element. > This element expresses the value contained in a cell. If the cell @@ -131,7 +131,7 @@ introduces Cell Value (\<**c**\>) element. > "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 > expressed in the shared string table. > -> © ISO/IEC29500: 2008. +> © [!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](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.drawingspart.aspx) object using the [AddNewPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.openxmlpartcontainer.addnewpart.aspx) method, appends it to the worksheet, and saves the worksheet part. The code then adds a new [ChartPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.chartpart.aspx) object, appends a new [ChartSpace](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.chartpart.chartspace.aspx) object to the **ChartPart** object, and then appends a new [EditingLanguage](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.chartspace.editinglanguage.aspx) object to the **ChartSpace*** object that specifies the language for the chart is English-US. +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. ### [C#](#tab/cs-1) [!code-csharp[](../../samples/spreadsheet/insert_a_chartto/cs/Program.cs#snippet1)] @@ -153,10 +153,10 @@ 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](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.barchart.aspx) object with [BarDirectionValues](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.bardirectionvalues.aspx) object set to **Column** and [BarGroupingValues](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.bargroupingvalues.aspx) object set to **Clustered**. +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 then iterates through each key in the **Dictionary** class. For each key, it appends a -[BarChartSeries](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.barchartseries.aspx) object to the **BarChart** object and sets the [SeriesText](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.seriestext.aspx) object of the **BarChartSeries** object to equal the key. For each key, it appends a [NumberLiteral](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.numberliteral.aspx) object to the **Values** collection of the **BarChartSeries** object and sets the **NumberLiteral** object to equal the **Dictionary** class value corresponding to the key. +[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. ### [C#](#tab/cs-2) [!code-csharp[](../../samples/spreadsheet/insert_a_chartto/cs/Program.cs#snippet2)] @@ -166,7 +166,7 @@ The code then iterates through each key in the **Dictionary** class. For each ke *** -The code adds the [CategoryAxis](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.categoryaxis.aspx) object and [ValueAxis](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.valueaxis.aspx) object to the chart and sets the value of the following properties: [Scaling](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.scaling.aspx), [AxisPosition](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.axisposition.aspx), [TickLabelPosition](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.ticklabelposition.aspx), [CrossingAxis](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.crossingaxis.aspx), [Crosses](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.crosses.aspx), [AutoLabeled](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.autolabeled.aspx), [LabelAlignment](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.labelalignment.aspx), and [LabelOffset](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.labeloffset.aspx). It also adds the [Legend](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.chart.legend.aspx) object to the chart and saves the chart part. +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. ### [C#](#tab/cs-3) [!code-csharp[](../../samples/spreadsheet/insert_a_chartto/cs/Program.cs#snippet3)] @@ -176,7 +176,7 @@ The code adds the [CategoryAxis](https://msdn.microsoft.com/library/office/docum *** -The code positions the chart on the worksheet by creating a [WorksheetDrawing](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.drawingspart.worksheetdrawing.aspx) object and appending a **TwoCellAnchor** object. The **TwoCellAnchor** object specifies how to move or resize the chart if you move the rows and columns between the [FromMarker](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.spreadsheet.frommarker.aspx) and [ToMarker](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.spreadsheet.tomarker.aspx) anchors. The code then creates a [GraphicFrame](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.spreadsheet.graphicframe.aspx) object to contain the chart and names the chart "Chart 1," and saves the worksheet drawing. +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. ### [C#](#tab/cs-4) [!code-csharp[](../../samples/spreadsheet/insert_a_chartto/cs/Program.cs#snippet4)] 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 c86e7e9e..724397f3 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 @@ -26,8 +26,8 @@ document programmatically. ## How the Sample Code Works After opening the **SpreadsheetDocument** -document for editing, the code inserts a blank [Worksheet](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.worksheetpart.worksheet.aspx) object into a [SpreadsheetDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.aspx) document package. Then, -inserts a new [Cell](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.cell.aspx) object into the new worksheet and +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 inserts the specified text into that cell. ### [C#](#tab/cs-1) @@ -41,9 +41,9 @@ 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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sharedstringtable.aspx) object, the code creates +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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sharedstringitem.aspx) object that represents 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 @@ -58,8 +58,8 @@ it does not exist. The code adds a new **WorksheetPart** object to -the **WorkbookPart** object by using the [AddNewPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.openxmlpartcontainer.addnewpart.aspx) 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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheet.sheetid.aspx) object used within the spreadsheet +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 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 @@ -67,7 +67,7 @@ then appends the new **Sheet** object to the The following code inserts a new **Worksheet** object by adding a new **WorksheetPart** object -to the [WorkbookPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.workbookpart.aspx) object. +to the [WorkbookPart](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.workbookpart) object. ### [C#](#tab/cs-3) [!code-csharp[](../../samples/spreadsheet/insert_textto_a_cell/cs/Program.cs#snippet3)] @@ -82,7 +82,7 @@ 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** variable. It then inserts the new cell before the cell referenced by -**refCell** using the [InsertBefore](https://msdn.microsoft.com/library/office/documentformat.openxml.openxmlcompositeelement.insertbefore.aspx) method. +**refCell** using the [InsertBefore](/dotnet/api/documentformat.openxml.openxmlcompositeelement.insertbefore) method. In the following code, insert a new **Cell** object into a **Worksheet** object. 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 64d8c38c..1a15d501 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 @@ -28,7 +28,7 @@ programmatically. -------------------------------------------------------------------------------- ## Sample Code -The following code merges two adjacent cells in a **[SpreadsheetDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.row.aspx)** document package. When +The following code merges two adjacent cells in a **[SpreadsheetDocument](/dotnet/api/documentformat.openxml.spreadsheet.row)** 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 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 66645348..53950479 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 @@ -33,7 +33,7 @@ programmatically open a read-only spreadsheet document. -------------------------------------------------------------------------------- ## Getting a SpreadsheetDocument Object -In the Open XML SDK, the [SpreadsheetDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.aspx) class represents an +In the Open XML SDK, the [SpreadsheetDocument](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument) class represents an Excel document package. To create an Excel document, you create an instance of the **SpreadsheetDocument** class and populate it with parts. At a minimum, the document must have a @@ -42,16 +42,16 @@ 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()](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.open.aspx) overload methods. Several **Open** methods are provided, each with a different +[Open()](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.open) 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)](https://msdn.microsoft.com/library/office/cc562356.aspx)|Create an instance of the SpreadsheetDocument class from the specified file. -Open(Stream, Boolean)|[Open(Stream, Boolean](https://msdn.microsoft.com/library/office/cc562185.aspx)|Create an instance of the SpreadsheetDocument class from the specified IO stream. -Open(String, Boolean, OpenSettings)|[Open(String, Boolean, OpenSettings)](https://msdn.microsoft.com/library/office/ee880344.aspx)|Create an instance of the SpreadsheetDocument class from the specified file. -Open(Stream, Boolean, OpenSettings)|[Open(Stream, Boolean, OpenSettings)](https://msdn.microsoft.com/library/office/ee840773.aspx)|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)|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. 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 @@ -117,15 +117,15 @@ operation. --------------------------------------------------------------------------------- ## Basic Document Structure The basic document structure of a SpreadsheetML document consists of the -[Sheets](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheets.aspx) and [Sheet](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheet.aspx) elements, which reference the -worksheets in the [Workbook](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.workbook.aspx). A separate XML file is created -for each [Worksheet](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.worksheet.aspx). For example, the SpreadsheetML +[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 - + @@ -134,8 +134,8 @@ located in the Workbook.xml file and is as follows. ``` The worksheet XML files contain one or more block level elements such as -[SheetData](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheetdata.aspx). **sheetData** represents the cell table and contains -one or more [Row](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.row.aspx) elements. A **row** contains one or more [Cell](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.cell.aspx) elements. Each cell contains a [CellValue](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.cellvalue.aspx) element that represents the value +[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. @@ -162,7 +162,7 @@ the **workbook**, **sheets**, **sheet**, **worksheet**, and **sheetData** elemen SpreadsheetML Element|Open XML SDK Class|Description --|--|-- workbook|DocumentFormat.OpenXml.Spreadsheet.Workbook|The root element for the main document part. -sheets|DocumentFormat.OpenXml.Spreadsheet.Sheets|The container for the block level structures such as sheet, fileVersion, and others specified in the [ISO/IEC 29500](https://www.iso.org/standard/71691.html) specification. +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. 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 19b1c0e2..f977223a 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 @@ -39,7 +39,7 @@ Open XML SDK. ## The SpreadsheetDocument Object The basic document structure of a SpreadsheetML document consists of the -[Sheets](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheets.aspx) and [Sheet](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheet.aspx) elements, which reference the +[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 @@ -47,7 +47,7 @@ file and is shown in the following code example. ```xml - + @@ -56,8 +56,8 @@ file and is shown in the following code example. ``` The worksheet XML files contain one or more block level elements such as -[SheetData](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheetdata.aspx). **sheetData** represents the cell table and contains -one or more [Row](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.row.aspx) elements. A **row** contains one or more [Cell](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.cell.aspx) elements. Each cell contains a [CellValue](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.cellvalue.aspx) element that represents the value +[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 @@ -85,7 +85,7 @@ the **workbook**, **sheets**, **sheet**, **worksheet**, and **sheetData** elemen SpreadsheetML Element|Open XML SDK Class|Description --|--|-- workbook|DocumentFormat.OpenXml.Spreadsheet.Workbook|The root element for the main document part. -sheets|DocumentFormat.OpenXml.Spreadsheet.Sheets|The container for the block level structures such as sheet, fileVersion, and others specified in the [ISO/IEC 29500](https://www.iso.org/standard/71691.html) specification. +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. @@ -97,8 +97,8 @@ v|DocumentFormat.OpenXml.Spreadsheet.CellValue|The value of a cell. -------------------------------------------------------------------------------- ## 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)](https://msdn.microsoft.com/library/office/cc562372.aspx) method to -create a new [WorksheetPart](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.worksheet.worksheetpart.aspx). The following code example +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**. ### [C#](#tab/cs-2) 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 0c3e347b..a02ceeaf 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 @@ -19,8 +19,7 @@ ms.localizationpriority: medium This topic shows how to use the classes in the Open XML SDK for Office to programmatically retrieve a dictionary that contains the names -and ranges of all defined names in an Microsoft Excel 2010 or Microsoft -Excel 2013 workbook. It contains an example **GetDefinedNames** method +and ranges of all defined names in a Microsoft Excel workbook. It contains an example **GetDefinedNames** method to illustrate this task. ## GetDefinedNames Method @@ -28,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](https://msdn.microsoft.com/library/xfhwa508.aspx) +[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 4572bd72..aaa55f06 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 @@ -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](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.open.aspx) method and indicating that the document should be open for read-only access (the final **false** parameter value). Next the code retrieves a reference to the workbook part, by using the [WorkbookPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.workbookpart.aspx) property of the document. +The code opens the document, by using the [SpreadsheetDocument.Open](/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. ### [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](https://msd *** -To find the hidden rows or columns, the code must first retrieve a reference to the specified sheet, given its name. This is not as easy as you might think. The code must look through all the sheet-type descendants of the workbook part's [Workbook](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.workbookpart.workbook.aspx) property, examining the [Name](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheet.name.aspx) property of each sheet that it finds. -Note that this search simply looks through the relations of the workbook, and does not actually find a worksheet part. It simply finds a reference to a [Sheet](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheet.aspx) object, which contains information such as the name and [Id](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheet.id.aspx) property of the sheet. The simplest way to accomplish this is to use a LINQ query. +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. ### [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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.worksheet.worksheetpart.aspx) property by calling the [GetPartById](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.openxmlpartcontainer.getpartbyid.aspx) method of the [WorkbookPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.workbookpart.aspx) object. +The sheet information you already retrieved provides an **Id** property, and given that **Id** property, the code can retrieve a reference to the corresponding [WorksheetPart](/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. ### [C#](#tab/cs-5) [!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs#snippet3)] @@ -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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.column.min.aspx) and [Max](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.column.max.aspx) properties that describe the first and last columns in the group. Therefore, the code that retrieves the list of hidden columns starts the same as the code that retrieves hidden rows. However, it must iterate through the index values (looping each item in the collection of hidden columns, adding each index from the **Min** to the **Max** value, inclusively). +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). ### [C#](#tab/cs-8) [!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs#snippet5)] 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 87f77f01..21abf5a9 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 @@ -20,7 +20,7 @@ This topic shows how to use the classes in the Open XML SDK for Office to progra ## 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\](https://msdn2.microsoft.com/library/6sh2ey19)** instance with a reference to each hidden **Sheet** object. +You can use the **GetHiddenSheets** method, to retrieve a list of the hidden worksheets in a workbook. The **GetHiddenSheets** method accepts a single parameter, a string that indicates the path of the file that you want to examine. The method works with the workbook you specify, filling a **[List\](/dotnet/api/system.collections.generic.list-1)** instance with a reference to each hidden **Sheet** object. ## Retrieve the collection of worksheets @@ -39,7 +39,7 @@ The following code uses the **Descendants** generic method of the **Workbook** o 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**. -Given the collection that contains information about all the sheets, the following code uses the **[Where](https://msdn2.microsoft.com/library/bb301979)** function to filter the collection so that it contains only the sheets in which the **State** property is not null. If the **State** property is not null, the code looks for the **Sheet** objects in which the **State** property as a value, and where the value is either **SheetStateValues.Hidden** or **SheetStateValues.VeryHidden**. +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**. ### [C#](#tab/cs-5) [!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_worksheets/cs/Program.cs#snippet2)] 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 ccc65726..4960dcaf 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 @@ -19,7 +19,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 2010 or Microsoft Excel 2013 workbook, without loading +Microsoft Excel workbook, without loading the document into Excel. It contains an example **GetAllWorksheets** method to illustrate this task. @@ -43,8 +43,8 @@ examine. The method works with the workbook you specify, returning an instance of -the **[Sheets](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheets.aspx)** object, from which you can retrieve -a reference to each **[Sheet](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheet.aspx)** object. +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. -------------------------------------------------------------------------------- @@ -81,7 +81,7 @@ workbook). The code then continues by opening the document in read-only mode, and -retrieving a reference to the **[WorkbookPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.workbookpart.aspx)**. +retrieving a reference to the **[WorkbookPart](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.workbookpart)**. ### [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](https://msdn.microsoft.com/librar *** -To get access to the **[Workbook](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.workbook.aspx)** object, the code retrieves the value of the **[Workbook](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.workbookpart.workbook.aspx)** property from the **WorkbookPart**, and then retrieves a reference to the **Sheets** object from the **[Sheets](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.workbook.sheets.aspx)** property of the **Workbook**. The **Sheets** object contains the collection of **[Sheet](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheet.aspx)** objects that provide the method's return value. +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. ### [C#](#tab/cs-4) [!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_worksheets/cs/Program.cs#snippet5)] 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 a3ce0be8..b0058983 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 @@ -61,9 +61,9 @@ initializes it to null. ## Accessing the Cell -Next, the code opens the document by using the **[Open](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.open.aspx)** method, indicating that the document +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](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.workbookpart.aspx)** property of the document. +reference to the workbook part by using the **[WorkbookPart](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.workbookpart)** 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](https://msdn.micros 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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheet.name.aspx)** property of each sheet that it finds. +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. 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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheet.aspx)**, which contains information such as -the name and **[Id](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheet.id.aspx)** of the sheet. The simplest way to do +**[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 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](https://msdn.microsoft.com/library/bb340482.aspx) +Be aware that the [FirstOrDefault](/dotnet/api/system.linq.enumerable.firstordefault) 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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheet.id.aspx)** property, and given that **Id** property, the code can retrieve a reference to -the corresponding **[WorksheetPart](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.worksheet.worksheetpart.aspx)** by calling the workbook part -**[GetPartById](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.openxmlpartcontainer.getpartbyid.aspx)** method. +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. ### [C#](#tab/cs-5) [!code-csharp[](../../samples/spreadsheet/retrieve_the_values_of_cells/cs/Program.cs?name=snippet5)] @@ -109,8 +109,8 @@ the corresponding **[WorksheetPart](https://msdn.microsoft.com/library/office/do Just as when locating the named sheet, when locating the named cell, the -code uses the **[Descendants](https://msdn.microsoft.com/library/office/documentformat.openxml.openxmlelement.descendants.aspx)** method, searching for the first -match in which the **[CellReference](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.celltype.cellreference.aspx)** property equals the specified +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, or will contain a null reference. @@ -136,7 +136,7 @@ such as the following. ``` -The **[InnerText](https://msdn.microsoft.com/library/office/documentformat.openxml.openxmlelement.innertext.aspx)** property contains the content for +The **[InnerText](/dotnet/api/documentformat.openxml.openxmlelement.innertext)** property contains the content for the cell, and so the next block of code retrieves this value. ### [C#](#tab/cs-7) @@ -149,7 +149,7 @@ 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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.cell.aspx)** type provides a **[DataType](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.celltype.datatype.aspx)** property that indicates the type +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 @@ -165,7 +165,7 @@ 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](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.workbookpart.sharedstringtablepart.aspx)**. +reference to the single **[SharedStringTablePart](/dotnet/api/documentformat.openxml.packaging.workbookpart.sharedstringtablepart)**. ### [C#](#tab/cs-9) [!code-csharp[](../../samples/spreadsheet/retrieve_the_values_of_cells/cs/Program.cs#snippet9)] diff --git a/docs/spreadsheet/structure-of-a-spreadsheetml-document.md b/docs/spreadsheet/structure-of-a-spreadsheetml-document.md index 30a97e7a..dce41e7c 100644 --- a/docs/spreadsheet/structure-of-a-spreadsheetml-document.md +++ b/docs/spreadsheet/structure-of-a-spreadsheetml-document.md @@ -40,17 +40,17 @@ some of the important spreadsheet elements. | Package Part| Top Level SpreadsheetML Element | Open XML SDK Class | Description| |:------------|:--------------------------------|:-----------------------|:-----------| -| Workbook | workbook | [Workbook](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.workbook.aspx) | The root element for the main document part.| -| Worksheet | worksheet | [Worksheet](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.worksheet.aspx) | 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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.chartsheet.aspx) | 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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.table.aspx) | 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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.pivottabledefinition.aspx) | [PivotTableDefinition](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.pivottabledefinition.aspx) | 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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.pivotcachedefinition.aspx) | 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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.pivotcacherecords.aspx) | A cache of the source data of the PivotTable. For more information, see [Working with PivotTables](working-with-pivottables.md). | -| Calculation Chain | calcChain | [CalculationChain](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.calculationchain.aspx) | 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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sharedstringtable.aspx) | 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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.conditionalformatting.aspx) | 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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.cellformula.aspx) | 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 | 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). | -------------------------------------------------------------------------------- ## Minimum Workbook Scenario @@ -109,9 +109,9 @@ the Open XML SDK code to create a minimum workbook. ```xml - + - + ``` @@ -141,7 +141,7 @@ you run the Open XML SDK to create a minimum workbook. ```xml - + ``` diff --git a/docs/spreadsheet/working-with-conditional-formatting.md b/docs/spreadsheet/working-with-conditional-formatting.md index 03e8e612..b07efd75 100644 --- a/docs/spreadsheet/working-with-conditional-formatting.md +++ b/docs/spreadsheet/working-with-conditional-formatting.md @@ -16,7 +16,7 @@ ms.localizationpriority: medium --- # Working with conditional formatting -This topic discusses the Open XML SDK **[ConditionalFormatting](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.conditionalformatting.aspx)** class and how it +This topic discusses the Open XML SDK **[ConditionalFormatting](/dotnet/api/documentformat.openxml.spreadsheet.conditionalformatting)** 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)**. @@ -46,10 +46,10 @@ class. | **SpreadsheetML Element** | **Open XML SDK Class** | |---------------------------|------------------------------------------------------------------------------------------------------------------------------------------------| -| cfRule | [ConditionalFormattingRule](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.conditionalformattingrule.aspx) | -| dataBar | [DataBar](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.databar.aspx) | -| colorScale | [ColorScale](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.colorscale.aspx) | -| iconSet | [IconSet](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.iconset.aspx) | +| 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 @@ -59,7 +59,7 @@ Open XML File Format schema for SpreadsheetML documents. Use the **ConditionalFo individual \<**conditionalFormatting**\> elements in a SpreadsheetML document. -The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the **ConditionalFormatting** (\<**conditionalFormatting**\>) element. A Conditional Format is a format, such as cell shading or font color, @@ -77,7 +77,7 @@ applied to cells that match the criteria. ``` -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### Conditional Formatting Rule Class @@ -106,7 +106,7 @@ 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. -© ISO/IEC29500: 2008. +© [!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 @@ -154,7 +154,7 @@ default, 10% and 90% respectively.) The minimum difference in length (or increment amount) is 1 pixel. -© ISO/IEC29500: 2008. +© [!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 @@ -189,7 +189,7 @@ Example: ``` -© ISO/IEC29500: 2008. +© [!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 @@ -222,7 +222,7 @@ value is greater than or equal to the 67th percentile. ``` -© ISO/IEC29500: 2008. +© [!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 diff --git a/docs/spreadsheet/working-with-formulas.md b/docs/spreadsheet/working-with-formulas.md index 4e4ee6d3..08d63229 100644 --- a/docs/spreadsheet/working-with-formulas.md +++ b/docs/spreadsheet/working-with-formulas.md @@ -16,7 +16,7 @@ ms.localizationpriority: high --- # Working with formulas -This topic discusses the Open XML SDK [CellFormula](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.cellformula.aspx) class and how it relates to the +This topic discusses the Open XML SDK [CellFormula](/dotnet/api/documentformat.openxml.spreadsheet.cellformula) 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 @@ -42,9 +42,9 @@ 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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.cellvalue.aspx). +when the worksheet is opened. For more information about the **CellValue** class, see [CellValue](/dotnet/api/documentformat.openxml.spreadsheet.cellvalue). -The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the **cellFormula** (\<**f**\>) element. @@ -103,7 +103,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). -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] For more information about formula syntax see the ISO/IEC 29500 specification. @@ -116,7 +116,7 @@ and is contained in the "sheet1.xml" file. ```xml - + diff --git a/docs/spreadsheet/working-with-pivottables.md b/docs/spreadsheet/working-with-pivottables.md index 6e6f346c..eea2e369 100644 --- a/docs/spreadsheet/working-with-pivottables.md +++ b/docs/spreadsheet/working-with-pivottables.md @@ -17,11 +17,11 @@ ms.localizationpriority: high # Working with PivotTables -This topic discusses the Open XML SDK **[PivotTableDefinition](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.pivottabledefinition.aspx)** 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 **[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). ## PivotTable in SpreadsheetML -The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) 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** (\<**pivotTableDefinition**\>) element. PivotTables display aggregated views of data easily and in an understandable layout. Hundreds or thousands of pieces of underlying @@ -89,9 +89,9 @@ The following table lists the common Open XML SDK classes used when working with | **SpreadsheetML Element** | **Open XML SDK Class** | |---------------------------|-------------------------------------------------------------------------------------------------------------------| -| pivotField | [PivotField](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.pivotfield.aspx) | -| pivotCacheDefinition | [PivotCacheDefinition](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.pivotcachedefinition.aspx) | -| pivotCacheRecords | [PivotCacheRecords](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.pivotcacherecords.aspx) | +| 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 diff --git a/docs/spreadsheet/working-with-sheets.md b/docs/spreadsheet/working-with-sheets.md index c2ff499c..918df05c 100644 --- a/docs/spreadsheet/working-with-sheets.md +++ b/docs/spreadsheet/working-with-sheets.md @@ -16,7 +16,7 @@ ms.localizationpriority: high --- # Working with sheets -This topic discusses the Open XML SDK [Worksheet](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.worksheet.aspx), [Chartsheet](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.chartsheet.aspx), and [DialogSheet](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.dialogsheet.aspx) classes and how they relate to +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 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). @@ -24,7 +24,7 @@ SpreadsheetML document, see [Structure of a SpreadsheetML document](structure-of ## Sheets in SpreadsheetML -The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the **sheet** (\<**sheet**\>) element. Sheets are the central structures within a workbook, and are where the @@ -40,7 +40,7 @@ these are also included in the sheet definition on disk. Other types of sheets include chart sheets and dialog sheets. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ## Open XML SDK Worksheet Class @@ -80,7 +80,7 @@ simplify the logic required to insert a new sheetData collection into an existing (but empty) sheet, the sheetData collection is required, even when empty. -© ISO/IEC29500: 2008. +© [!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 @@ -105,14 +105,14 @@ 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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.worksheet.aspx) class. +working with the [Worksheet](/dotnet/api/documentformat.openxml.spreadsheet.worksheet) class. | **SpreadsheetML Element** | **Open XML SDK Class** | |---|---| -| sheetData | [SheetData](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheetdata.aspx) | -| row | [Row](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.row.aspx) | -| c | [Cell](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.cell.aspx) | -| v | [CellValue](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.cellvalue.aspx) | +| 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 @@ -126,7 +126,7 @@ introduces the **sheet data** (\<**sheetData**\>) element. The cell table is the core structure of a worksheet. It consists of all the text, numbers, and formulas in the grid. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### Row Class @@ -138,7 +138,7 @@ The cells in the cell table are organized by row. Each row has an index 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. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### Cell Class @@ -152,7 +152,7 @@ also indicate a style identifier (attribute s) and a data type order to optimize load/save operations, default data values are not written out. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### CellValue Class @@ -172,7 +172,7 @@ 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. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### Open XML SDK Code Example @@ -195,7 +195,7 @@ the "sheet.xml" file in the "worksheets" folder of the .zip file. ```xml - + @@ -227,14 +227,14 @@ relationship in the Chartsheet part's relationship item: ``` -© ISO/IEC29500: 2008. +© [!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](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.chartsheet.aspx) class. +working with the [Chartsheet](/dotnet/api/documentformat.openxml.spreadsheet.chartsheet) class. | **SpreadsheetML Element** | **Open XML SDK Class** | |---|---| -| drawing | [Drawing](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.drawing.aspx) | +| drawing | [Drawing](/dotnet/api/documentformat.openxml.spreadsheet.drawing) | ### Drawing Class @@ -250,7 +250,7 @@ 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. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ## Open XML SDK Dialogsheet Class @@ -280,4 +280,4 @@ Example: sheet1.xml contains the following: ``` -© ISO/IEC29500: 2008. +© [!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 0eae2c08..5aba0b64 100644 --- a/docs/spreadsheet/working-with-tables.md +++ b/docs/spreadsheet/working-with-tables.md @@ -17,7 +17,7 @@ ms.localizationpriority: high # Working with SpreadsheetML tables -This topic discusses the Open XML SDK **[Table](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.table.aspx)** class and how it relates to the Open +This topic discusses the Open XML SDK **[Table](/dotnet/api/documentformat.openxml.spreadsheet.table)** 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 @@ -25,7 +25,7 @@ document, see [Structure of a SpreadsheetML document ## Tables in SpreadsheetML -The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) 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** (\<**table**\>) element. A table helps organize and provide structure to lists of information in a worksheet. Tables have clearly labeled columns, rows, and data @@ -68,8 +68,8 @@ The following table lists the common Open XML SDK classes used when working with | **SpreadsheetML Element** | **Open XML SDK Class** | |---------------------------|------------------------------------------------------------------------------------------------------------------------| -| tableColumn | [TableColumn](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.tablecolumn.aspx) | -| autoFilter | [AutoFilter](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.table.autofilter.aspx) | +| tableColumn | [TableColumn](/dotnet/api/documentformat.openxml.spreadsheet.tablecolumn) | +| autoFilter | [AutoFilter](/dotnet/api/documentformat.openxml.spreadsheet.table.autofilter) | ## Open XML SDK Table Class @@ -156,7 +156,7 @@ displayed in the table, and contains the **tablePart** element that references t ```xml - + diff --git a/docs/spreadsheet/working-with-the-calculation-chain.md b/docs/spreadsheet/working-with-the-calculation-chain.md index 2ad9110a..47b33de0 100644 --- a/docs/spreadsheet/working-with-the-calculation-chain.md +++ b/docs/spreadsheet/working-with-the-calculation-chain.md @@ -16,7 +16,7 @@ ms.localizationpriority: high --- # Working with the calculation chain -This topic discusses the Open XML SDK [CalculationChain](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.calculationchain.aspx) class and how it relates +This topic discusses the Open XML SDK [CalculationChain](/dotnet/api/documentformat.openxml.spreadsheet.calculationchain) 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). @@ -24,7 +24,7 @@ SpreadsheetML document, see [Structure of a SpreadsheetML document](structure-of ## CalculationChain in SpreadsheetML -The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the **CalculationChain** (\<**calcChain**\>) element. An instance of this part type contains an ordered set of references to @@ -67,7 +67,7 @@ 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. -© ISO/IEC29500: 2008. +© [!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. @@ -101,7 +101,7 @@ 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. -© ISO/IEC29500: 2008. +© [!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 4a6d71a3..b299e957 100644 --- a/docs/spreadsheet/working-with-the-shared-string-table.md +++ b/docs/spreadsheet/working-with-the-shared-string-table.md @@ -16,7 +16,7 @@ ms.localizationpriority: high --- # Working with the shared string table -This topic discusses the Open XML SDK [SharedStringTable](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sharedstringtable.aspx) class and how it relates +This topic discusses the Open XML SDK [SharedStringTable](/dotnet/api/documentformat.openxml.spreadsheet.sharedstringtable) 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). @@ -24,7 +24,7 @@ SpreadsheetML document, see [Structure of a SpreadsheetML document](structure-of -------------------------------------------------------------------------------- ## SharedStringTable in SpreadsheetML -The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the **SharedStringTable** (\<**sst**\>) element. An instance of this part type contains one occurrence of each unique @@ -41,7 +41,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. -© ISO/IEC29500: 2008. +© [!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 @@ -74,8 +74,8 @@ working with the **SharedStringTable** class. | **SpreadsheetML Element** | **Open XML SDK Class** | |---------------------------|------------------------------------------------------------------------------------------------------------------------------| -| si | [SharedStringItem](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sharedstringitem.aspx) | -| t | [Text](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.text.aspx) | +| si | [SharedStringItem](/dotnet/api/documentformat.openxml.spreadsheet.sharedstringitem) | +| t | [Text](/dotnet/api/documentformat.openxml.spreadsheet.text) | -------------------------------------------------------------------------------- ## Open XML SDK SharedStringTable Class @@ -222,7 +222,7 @@ referenced in the code. ```xml - + hello @@ -232,7 +232,7 @@ In addition, the following XML is written to the new worksheet XML file. ```xml - + 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 969a3b3a..0bf65264 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 @@ -23,7 +23,7 @@ This topic shows how to use the Open XML SDK for Office to accept all revisions 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](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.aspx) 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 [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. | WordprocessingML Element | Open XML SDK Class | Description | |---|---|---| -| document | [Document](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.document.aspx) | The root element for the main document part. | -| body | [Body](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.body.aspx) | The container for the block level structures such as paragraphs, tables, annotations and others specified in the [ISO/IEC 29500](https://www.iso.org/standard/71691.html) specification. | -| p | [Paragraph](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.paragraph.aspx) | A paragraph. | -| r | [Run](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.run.aspx) | A run. | -| t | [Text](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.text.aspx) | A range of text. | +| 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. | ## 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. -The following information from the [ISO/IEC 29500](https://www.iso.org/standard/71691.html) 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) @@ -73,11 +73,11 @@ 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** -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ## Deleted Element -The following information from the [ISO/IEC 29500](https://www.iso.org/standard/71691.html) specification +The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the Deleted element (**del**). ### del (Deleted Paragraph) @@ -113,11 +113,11 @@ 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. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ## The Inserted Element -The following information from the [ISO/IEC 29500](https://www.iso.org/standard/71691.html) specification +The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the Inserted element (**ins**). ### ins (Inserted Table Row) @@ -160,7 +160,7 @@ 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. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ## Sample Code 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 c2fdf7d3..a04e7ab0 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 @@ -41,9 +41,9 @@ The following sections in this topic explain the implementation of this method a ## Get a WordprocessingDocument object -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 [WordprocessingDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.aspx) class represents a Word document package. To open and work with a Word document, create an instance of the **WordprocessingDocument** 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. +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 [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) class represents a Word document package. To open and work with a Word document, create an instance of the **WordprocessingDocument** 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()](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.open.aspx) method. The following sample code shows how to use the [WordprocessingDocument.Open](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.open.aspx) overload. The first parameter takes a string that represents the full path to the document to open. The second parameter takes a value of **true** or **false** and represents whether 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 [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. ### [C#](#tab/cs-1) ```csharp @@ -68,7 +68,7 @@ To create the class instance, call one of the overloads of the [Open()](https:// ## 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](https://msdn.microsoft.com/library/bb494386.aspx) 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 [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. ### [C#](#tab/cs-2) ```csharp @@ -99,7 +99,7 @@ After opening the file, the sample code retrieves a reference to the first parag 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](https://msdn.microsoft.com/library/bb494386.aspx) +[ElementAtOrDefault](/dotnet/api/system.linq.enumerable.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. @@ -135,7 +135,7 @@ following sample markup shows a pStyle element that specifies the "OverdueAmount" style. ```xml - + @@ -144,10 +144,10 @@ following sample markup shows a pStyle element that specifies the ``` In the Open XML SDK, the **pPr** element is -represented by the [ParagraphProperties](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.paragraphproperties.aspx) class. The code +represented by the [ParagraphProperties](/dotnet/api/documentformat.openxml.wordprocessing.paragraphproperties) 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)](https://msdn.microsoft.com/library/office/cc883719.aspx) method is used to add +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 the instance, as shown in the following code example. ### [C#](#tab/cs-3) @@ -221,7 +221,7 @@ 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](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.styles.aspx) class in the Open XML SDK. Finally, +element is represented by the [Styles](/dotnet/api/documentformat.openxml.wordprocessing.styles) class in the Open XML SDK. Finally, the code saves the part. ### [C#](#tab/cs-5) @@ -327,7 +327,7 @@ to add the style. Within the **IsStyleInDocument** example -method, the work begins with retrieving the **Styles** element through the **Styles** property of the [StyleDefinitionsPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.maindocumentpart.styledefinitionspart.aspx) of the main document +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 part, and then determining whether any styles exist as children of that element. All style elements are stored as children of the styles element. @@ -337,7 +337,7 @@ 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](https://msdn.microsoft.com/library/bb340482.aspx) +[FirstOrDefault](/dotnet/api/system.linq.enumerable.firstordefault) 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. @@ -409,8 +409,8 @@ The second parameter takes the styleid of the style, and the third parameter takes the style name. The **AddNewStyle** code creates the named style definition within the specified part. -To create the style, the code instantiates the [Style](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.style.aspx) class and sets certain properties, -such as the [Type](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.style.type.aspx) of style (paragraph) and [StyleId](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.style.styleid.aspx). As mentioned above, the styleid is +To create the style, the code instantiates the [Style](/dotnet/api/documentformat.openxml.wordprocessing.style) class and sets certain properties, +such as the [Type](/dotnet/api/documentformat.openxml.wordprocessing.style.type) of style (paragraph) and [StyleId](/dotnet/api/documentformat.openxml.wordprocessing.style.styleid). As mentioned above, the styleid is used by 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. A style can also have a separate user friendly style name to be @@ -435,7 +435,7 @@ the font and color characteristics for the runs in a paragraph, you use the run properties. To create the **rPr** element with the -appropriate child elements, the code creates an instance of the [StyleRunProperties](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.stylerunproperties.aspx) class and then appends +appropriate child elements, the code creates an instance of the [StyleRunProperties](/dotnet/api/documentformat.openxml.wordprocessing.stylerunproperties) class and then appends instances of the appropriate property classes. For this code example, the style specifies the Lucida Console font, a point size of 12, rendered in bold and italic, using the Accent2 color from the document @@ -539,7 +539,7 @@ Now, the example code has located the paragraph, added the required paragraph properties element if required, checked for the styles part and added it if required, and checked for the style and added it if required. Now, set the paragraph style. To accomplish this task, the -code creates an instance of the [ParagraphStyleId](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.paragraphstyleid.aspx) class with the styleid and +code creates an instance of the [ParagraphStyleId](/dotnet/api/documentformat.openxml.wordprocessing.paragraphstyleid) class with the styleid and then places a reference to that instance in the **ParagraphStyleId** property of the paragraph properties object. This creates and assigns the appropriate value to the **pStyle** element that specifies the style to use for the paragraph. diff --git a/docs/word/how-to-change-text-in-a-table-in-a-word-processing-document.md b/docs/word/how-to-change-text-in-a-table-in-a-word-processing-document.md index d0276a7d..1e92cd22 100644 --- a/docs/word/how-to-change-text-in-a-table-in-a-word-processing-document.md +++ b/docs/word/how-to-change-text-in-a-table-in-a-word-processing-document.md @@ -210,7 +210,7 @@ Following is the complete code example. ## See also [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) -[How to: Change Text in a Table in a Word Processing Document](https://msdn.microsoft.com/library/documentformat.openxml.wordprocessing.table(office.14).aspx) -[Language-Integrated Query (LINQ)](https://msdn.microsoft.com/library/bb397926.aspx) -[Extension Methods (C\# Programming Guide)](https://msdn.microsoft.com/library/bb383977.aspx) -[Extension Methods (Visual Basic)](https://msdn.microsoft.com/library/bb384936.aspx) +[How to: Change Text in a Table in a Word Processing Document](/previous-versions/office/developer/office-2010/cc840870(v=office.14)) +[Language-Integrated Query (LINQ)](/previous-versions/bb397926(v=vs.140)) +[Extension Methods (C\# Programming Guide)](/dotnet/csharp/programming-guide/classes-and-structs/extension-methods) +[Extension Methods (Visual Basic)](/dotnet/visual-basic/programming-guide/language-features/procedures/extension-methods) diff --git a/docs/word/how-to-change-the-print-orientation-of-a-word-processing-document.md b/docs/word/how-to-change-the-print-orientation-of-a-word-processing-document.md index eeb353a4..75bf8f58 100644 --- a/docs/word/how-to-change-the-print-orientation-of-a-word-processing-document.md +++ b/docs/word/how-to-change-the-print-orientation-of-a-word-processing-document.md @@ -19,8 +19,7 @@ ms.localizationpriority: medium # Change the print orientation of a word processing document This topic shows how to use the classes in the Open XML SDK for -Office to programmatically set the print orientation of a Microsoft Word -2010 or Microsoft Word 2013 document. It contains an example +Office to programmatically set the print orientation of a Microsoft Word document. It contains an example **SetPrintOrientation** method to illustrate this task. @@ -32,7 +31,7 @@ Office to programmatically set the print orientation of a Microsoft Word You can use the **SetPrintOrientation** method to change the print orientation of a word processing document. The method accepts two parameters that indicate the name of the document to -modify (string) and the new print orientation ([PageOrientationValues](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.pageorientationvalues.aspx)). +modify (string) and the new print orientation ([PageOrientationValues](/dotnet/api/documentformat.openxml.wordprocessing.pageorientationvalues)). The following code shows the **SetPrintOrientation** method. @@ -82,13 +81,13 @@ following code shows an example method call. ## How the Code Works -The following code first opens the document by using the [Open](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.open.aspx) method and sets the **isEditable** parameter to +The following code first opens the document by using the [Open](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) method and sets the **isEditable** parameter to **true** to indicate that the document should be read/write. The code maintains a Boolean variable that tracks whether the document has changed (so that it can save the document later, if the document has changed). The code retrieves a reference to the main document part, and then uses that reference to retrieve a collection of -all of the descendants of type [SectionProperties](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.sectionproperties.aspx) within the content of the +all of the descendants of type [SectionProperties](/dotnet/api/documentformat.openxml.wordprocessing.sectionproperties) within the content of the document. Later code will use this collection to set the orientation for each section in turn. @@ -123,7 +122,7 @@ each section in turn. ## Iterating Through All the Sections -The next block of code iterates through all the sections in the collection of **SectionProperties** elements. For each section, the code initializes a variable that tracks whether the page orientation for the section was changed so the code can update the page size and margins. (If the new orientation matches the original orientation, the code will not update the page.) The code continues by retrieving a reference to the first [PageSize](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.pagesize.aspx) descendant of the **SectionProperties** element. If the reference is not null, the code updates the orientation as required. +The next block of code iterates through all the sections in the collection of **SectionProperties** elements. For each section, the code initializes a variable that tracks whether the page orientation for the section was changed so the code can update the page size and margins. (If the new orientation matches the original orientation, the code will not update the page.) The code continues by retrieving a reference to the first [PageSize](/dotnet/api/documentformat.openxml.wordprocessing.pagesize) descendant of the **SectionProperties** element. If the reference is not null, the code updates the orientation as required. ### [C#](#tab/cs-3) ```csharp @@ -159,7 +158,7 @@ The next block of code iterates through all the sections in the collection of ** ## Setting the Orientation for the Section -The next block of code first checks whether the [Orient](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.pagesize.orient.aspx) property of the **PageSize** element exists. As with many properties +The next block of code first checks whether the [Orient](/dotnet/api/documentformat.openxml.wordprocessing.pagesize.orient) property of the **PageSize** element exists. As with many properties of Open XML elements, the property or attribute might not exist yet. In that case, retrieving the property returns a null reference. By default, if the property does not exist, and the new orientation is Portrait, the @@ -172,7 +171,7 @@ must update the page size and margins. It uses the **documentChanged** flag to d save the document at the end.) > [!NOTE] -> If the code must create the **Orient** property, it must also create the value to store in the property, as a new [EnumValue\](https://msdn.microsoft.com/library/office/cc801792.aspx) instance, supplying the new orientation in the **EnumValue** constructor. +> If the code must create the **Orient** property, it must also create the value to store in the property, as a new [EnumValue\](/dotnet/api/documentformat.openxml.enumvalue-1) instance, supplying the new orientation in the **EnumValue** constructor. ### [C#](#tab/cs-4) ```csharp @@ -262,12 +261,12 @@ in the **PageSize** element. The next step in the sample procedure handles margins for the section. If the page orientation has changed, the code must rotate the margins to -match. To do so, the code retrieves a reference to the [PageMargin](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.pagemargin.aspx) element for the section. If the +match. To do so, the code retrieves a reference to the [PageMargin](/dotnet/api/documentformat.openxml.wordprocessing.pagemargin) element for the section. If the element exists, the code rotates the margins. Note that the code rotates the margins by 90 degrees—some printers rotate the margins by 270 degrees instead and you could modify the code to take that into account. -Also be aware that the [Top](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.pagemargin.top.aspx) and [Bottom](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.pagemargin.bottom.aspx) properties of the **PageMargin** object are signed values, and the -[Left](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.pagemargin.left.aspx) and [Right](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.pagemargin.right.aspx) properties are unsigned values. The +Also be aware that the [Top](/dotnet/api/documentformat.openxml.wordprocessing.pagemargin.top) and [Bottom](/dotnet/api/documentformat.openxml.wordprocessing.pagemargin.bottom) properties of the **PageMargin** object are signed values, and the +[Left](/dotnet/api/documentformat.openxml.wordprocessing.pagemargin.left) and [Right](/dotnet/api/documentformat.openxml.wordprocessing.pagemargin.right) properties are unsigned values. The code must convert between the two types of values as it rotates the margin settings, as shown in the following code. diff --git a/docs/word/how-to-convert-a-word-processing-document-from-the-docm-to-the-docx-file-format.md b/docs/word/how-to-convert-a-word-processing-document-from-the-docm-to-the-docx-file-format.md index 3b7905c7..645aa7ad 100644 --- a/docs/word/how-to-convert-a-word-processing-document-from-the-docm-to-the-docx-file-format.md +++ b/docs/word/how-to-convert-a-word-processing-document-from-the-docm-to-the-docx-file-format.md @@ -20,8 +20,7 @@ ms.localizationpriority: high # Convert a word processing document from the DOCM to the DOCX file format This topic shows how to use the classes in the Open XML SDK for -Office to programmatically convert a Microsoft Word 2010 or Microsoft -Word 2013 document that contains VBA code (and has a .docm extension) to +Office to programmatically convert a Microsoft Word document that contains VBA code (and has a .docm extension) to a standard document (with a .docx extension). It contains an example **ConvertDOCMtoDOCX** method to illustrate this task. @@ -29,8 +28,7 @@ a standard document (with a .docx extension). It contains an example ## ConvertDOCMtoDOCX Method -The **ConvertDOCMtoDOCX** sample method can be used to convert a Word -2010 or Word 2013 document that contains VBA code (and has a .docm +The **ConvertDOCMtoDOCX** sample method can be used to convert a Word document that contains VBA code (and has a .docm extension) to a standard document (with a .docx extension). Use this method to remove the macros and the vbaProject part that contains them from a document stored in .docm file format. The method accepts a single diff --git a/docs/word/how-to-create-a-word-processing-document-by-providing-a-file-name.md b/docs/word/how-to-create-a-word-processing-document-by-providing-a-file-name.md index a4f5ea11..ed8c7ce9 100644 --- a/docs/word/how-to-create-a-word-processing-document-by-providing-a-file-name.md +++ b/docs/word/how-to-create-a-word-processing-document-by-providing-a-file-name.md @@ -23,7 +23,7 @@ Office to programmatically create a word processing document. -------------------------------------------------------------------------------- ## Creating a WordprocessingDocument Object -In the Open XML SDK, the [WordprocessingDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.aspx) class represents a +In the Open XML SDK, the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) class represents a Word document package. To create a Word document, you create an instance of the **WordprocessingDocument** class and populate it with parts. At a minimum, the document must have a main @@ -31,12 +31,12 @@ 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. -To create the class instance you call the [Create(String, WordprocessingDocumentType)](https://msdn.microsoft.com/library/office/cc535610.aspx) -method. Several [Create()](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.create.aspx) methods are provided, each with a +To create the class instance you call the [Create(String, WordprocessingDocumentType)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.create) +method. Several [Create()](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.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 takes a full path string that represents the document that you want to create. The second parameter is a member -of the [WordprocessingDocumentType](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessingdocumenttype.aspx) enumeration. +of the [WordprocessingDocumentType](/dotnet/api/documentformat.openxml.wordprocessingdocumenttype) enumeration. This parameter represents the type of document. For example, there is a different member of the **WordProcessingDocumentType** enumeration for each of document, template, and the macro enabled variety of document and @@ -81,7 +81,7 @@ exit the bracketed block, you do not have to explicitly call **Save** and **Clos long as you use **using**. Once you have created the Word document package, you can add parts to -it. To add the main document part you call the [AddMainDocumentPart()](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.addmaindocumentpart.aspx) method of the **WordprocessingDocument** class. Having done that, +it. To add the main document part you call the [AddMainDocumentPart()](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.addmaindocumentpart) method of the **WordprocessingDocument** class. Having done that, you can set about adding the document structure and text. diff --git a/docs/word/how-to-create-and-add-a-character-style-to-a-word-processing-document.md b/docs/word/how-to-create-and-add-a-character-style-to-a-word-processing-document.md index b2331097..71da7845 100644 --- a/docs/word/how-to-create-and-add-a-character-style-to-a-word-processing-document.md +++ b/docs/word/how-to-create-and-add-a-character-style-to-a-word-processing-document.md @@ -225,7 +225,7 @@ second run. WordprocessingML supports six style types, four of which you can specify using the type attribute on the style element. The following -information, from section 17.7.4.17 in the [ISO/IEC 29500](https://www.iso.org/standard/71691.html) specification, +information, from section 17.7.4.17 in the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification, introduces style types. *Style types* refers to the property on a style which defines the type @@ -325,8 +325,8 @@ styles element is created and saved to the part. ## Creating the Style -To create the style, the code instantiates the [Style](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.style.aspx) class and sets certain properties, -such as the [Type](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.style.type.aspx) of style (paragraph), the [StyleId](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.style.styleid.aspx), and whether the style is a [CustomStyle](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.style.customstyle.aspx). +To create the style, the code instantiates the [Style](/dotnet/api/documentformat.openxml.wordprocessing.style) class and sets certain properties, +such as the [Type](/dotnet/api/documentformat.openxml.wordprocessing.style.type) of style (paragraph), the [StyleId](/dotnet/api/documentformat.openxml.wordprocessing.style.styleid), and whether the style is a [CustomStyle](/dotnet/api/documentformat.openxml.wordprocessing.style.customstyle). ### [C#](#tab/cs-3) ```csharp @@ -353,15 +353,15 @@ such as the [Type](https://msdn.microsoft.com/library/office/documentformat.open The code results in the following XML. ```xml - + ``` The code next creates the child elements of the style, which define the properties of the style. To create an element, you instantiate its -corresponding class, and then call the [Append(\[\])](https://msdn.microsoft.com/library/office/cc801361.aspx) method to add the child element +corresponding class, and then call the [Append(\[\])](/dotnet/api/documentformat.openxml.openxmlelement.append) method to add the child element to the style. For more information about these properties, see section -17.7 of the [ISO/IEC 29500](https://www.iso.org/standard/71691.html) specification. +17.7 of the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification. ### [C#](#tab/cs-4) ```csharp @@ -390,7 +390,7 @@ to the style. For more information about these properties, see section *** -Next, the code instantiates a [StyleRunProperties](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.stylerunproperties.aspx) object to create a **rPr** (Run Properties) element. You specify the +Next, the code instantiates a [StyleRunProperties](/dotnet/api/documentformat.openxml.wordprocessing.stylerunproperties) object to create a **rPr** (Run Properties) element. You specify the character properties that apply to the style, such as font and color, in this element. The properties are then appended as children of the **rPr** element. @@ -449,7 +449,7 @@ to the styles root element in the styles part. The following XML shows the final style generated by the code shown here. ```xml - + diff --git a/docs/word/how-to-create-and-add-a-paragraph-style-to-a-word-processing-document.md b/docs/word/how-to-create-and-add-a-paragraph-style-to-a-word-processing-document.md index 20b5e2fc..1ec0f0f8 100644 --- a/docs/word/how-to-create-and-add-a-paragraph-style-to-a-word-processing-document.md +++ b/docs/word/how-to-create-and-add-a-paragraph-style-to-a-word-processing-document.md @@ -222,7 +222,7 @@ applies the style to the paragraph. WordprocessingML supports six style types, four of which you can specify using the type attribute on the style element. The following -information, from section 17.7.4.17 in the [ISO/IEC 29500](https://www.iso.org/standard/71691.html) specification, +information, from section 17.7.4.17 in the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification, introduces style types. *Style types* refers to the property on a style which defines the type @@ -261,7 +261,7 @@ type attribute: The type attribute has a value of paragraph, which indicates that the following style definition is a paragraph style. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] You can set the paragraph, character, table and numbering styles types by specifying the corresponding value in the type attribute of the style @@ -309,7 +309,7 @@ The paragraph style is then applied to paragraphs by referencing the styleId attribute value for this style in the paragraph properties' **pStyle** element. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] --------------------------------------------------------------------------------- @@ -348,9 +348,9 @@ styles element is created and saved to the part. ## Creating the Style -To create the style, the code instantiates the **[Style](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.style.aspx)** class and sets certain properties, -such as the **[Type](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.style.type.aspx)** of style (paragraph), the **[StyleId](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.style.styleid.aspx)**, whether the style is a **[CustomStyle](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.style.customstyle.aspx)**, and whether the style is the -**[Default](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.style.default.aspx)** style for its type. +To create the style, the code instantiates the **[Style](/dotnet/api/documentformat.openxml.wordprocessing.style)** class and sets certain properties, +such as the **[Type](/dotnet/api/documentformat.openxml.wordprocessing.style.type)** of style (paragraph), the **[StyleId](/dotnet/api/documentformat.openxml.wordprocessing.style.styleid)**, whether the style is a **[CustomStyle](/dotnet/api/documentformat.openxml.wordprocessing.style.customstyle)**, and whether the style is the +**[Default](/dotnet/api/documentformat.openxml.wordprocessing.style.default)** style for its type. ### [C#](#tab/cs-3) ```csharp @@ -376,7 +376,7 @@ such as the **[Type](https://msdn.microsoft.com/library/office/documentformat.op The code results in the following XML. ```xml - + @@ -384,9 +384,9 @@ The code results in the following XML. The code next creates the child elements of the style, which define the properties of the style. To create an element, you instantiate its -corresponding class, and then call the **[Append([])](https://msdn.microsoft.com/library/office/cc801361.aspx)** method add the child element to +corresponding class, and then call the **[Append([])](/dotnet/api/documentformat.openxml.openxmlelement.append)** method add the child element to the style. For more information about these properties, see section 17.7 -of the [ISO/IEC 29500](https://www.iso.org/standard/71691.html) +of the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification. ### [C#](#tab/cs-4) @@ -454,7 +454,7 @@ specification. *** -Next, the code instantiates a **[StyleRunProperties](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.stylerunproperties.aspx)** object to create a **rPr** (Run Properties) element. You specify the character properties that apply to the style, such as font and color, in this element. The properties are then appended as children of the **rPr** element. +Next, the code instantiates a **[StyleRunProperties](/dotnet/api/documentformat.openxml.wordprocessing.stylerunproperties)** object to create a **rPr** (Run Properties) element. You specify the character properties that apply to the style, such as font and color, in this element. The properties are then appended as children of the **rPr** element. When the run properties are created, the code appends the **rPr** element to the style, and the style element to the styles root element in the styles part. diff --git a/docs/word/how-to-delete-comments-by-all-or-a-specific-author-in-a-word-processing-document.md b/docs/word/how-to-delete-comments-by-all-or-a-specific-author-in-a-word-processing-document.md index 0b84cfbb..c8ee6ffa 100644 --- a/docs/word/how-to-delete-comments-by-all-or-a-specific-author-in-a-word-processing-document.md +++ b/docs/word/how-to-delete-comments-by-all-or-a-specific-author-in-a-word-processing-document.md @@ -78,12 +78,12 @@ the required parameters as shown in the following code. -------------------------------------------------------------------------------- ## How the Code Works -The following code starts by opening the document, using the [WordprocessingDocument.Open](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.open.aspx) method and +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 comments part, using the [WordprocessingCommentsPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.maindocumentpart.wordprocessingcommentspart.aspx) property of the +retrieves a reference to the comments part, using the [WordprocessingCommentsPart](/dotnet/api/documentformat.openxml.packaging.maindocumentpart.wordprocessingcommentspart) property of the main document part, after having retrieved a reference to the main -document part from the [MainDocumentPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.maindocumentpart.aspx) property of the word +document part from the [MainDocumentPart](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.maindocumentpart) property of the word processing document. If the comments part is missing, there is no point in proceeding, as there cannot be any comments to delete. @@ -138,8 +138,8 @@ delete, and creating a list of comment IDs that correspond to the comments to delete. Given these lists, the code can both delete the comments from the comments part that contains the comments, and delete the references to the comments from the document part.The following code -starts by retrieving a list of [Comment](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.comment.aspx) elements. To retrieve the list, it -converts the [Elements](https://msdn.microsoft.com/library/office/documentformat.openxml.openxmlelement.elements.aspx) collection exposed by the **commentPart** variable into a list of **Comment** objects. +starts by retrieving a list of [Comment](/dotnet/api/documentformat.openxml.wordprocessing.comment) elements. To retrieve the list, it +converts the [Elements](/dotnet/api/documentformat.openxml.openxmlelement.elements) collection exposed by the **commentPart** variable into a list of **Comment** objects. ### [C#](#tab/cs-3) ```csharp @@ -157,7 +157,7 @@ converts the [Elements](https://msdn.microsoft.com/library/office/documentformat So far, the list of comments contains all of the comments. If the author parameter is not an empty string, the following code limits the list to -only those comments where the [Author](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.comment.author.aspx) property matches the parameter you +only those comments where the [Author](/dotnet/api/documentformat.openxml.wordprocessing.comment.author) property matches the parameter you supplied. ### [C#](#tab/cs-4) @@ -181,8 +181,8 @@ supplied. Before deleting any comments, the code retrieves a list of comments ID values, so that it can later delete matching elements from the document -part. The call to the [Select](https://msdn2.microsoft.com/library/bb357126) -method effectively projects the list of comments, retrieving an [IEnumerable\](https://msdn2.microsoft.com/library/9eekhta0) +part. The call to the [Select](/dotnet/api/system.linq.enumerable.select) +method effectively projects the list of comments, retrieving an [IEnumerable\](/dotnet/api/system.collections.generic.ienumerable-1) of strings that contain all the comment ID values. ### [C#](#tab/cs-5) @@ -241,7 +241,7 @@ and performs the deletion. The code then saves the comments part. Although the code has successfully removed all the comments by this point, that is not enough. The code must also remove references to the comments from the document part. This action requires three steps -because the comment reference includes the [CommentRangeStart](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.commentrangestart.aspx), [CommentRangeEnd](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.commentrangeend.aspx), and [CommentReference](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.commentreference.aspx) elements, and the code +because the comment reference includes the [CommentRangeStart](/dotnet/api/documentformat.openxml.wordprocessing.commentrangestart), [CommentRangeEnd](/dotnet/api/documentformat.openxml.wordprocessing.commentrangeend), and [CommentReference](/dotnet/api/documentformat.openxml.wordprocessing.commentreference) elements, and the code must remove all three for each comment. Before performing any deletions, the code first retrieves a reference to the root element of the main document part, as shown in the following code. @@ -262,7 +262,7 @@ Given a reference to the document element, the following code performs its deletion loop three times, once for each of the different elements it must delete. In each case, the code looks for all descendants of the correct type (**CommentRangeStart**, **CommentRangeEnd**, or **CommentReference**) and limits the list to those -whose [Id](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.markuprangetype.id.aspx) property value is contained in the list +whose [Id](/dotnet/api/documentformat.openxml.wordprocessing.markuprangetype.id) property value is contained in the list of comment IDs to be deleted. Given the list of elements to be deleted, the code removes each element in turn. Finally, the code completes by saving the document. diff --git a/docs/word/how-to-extract-styles-from-a-word-processing-document.md b/docs/word/how-to-extract-styles-from-a-word-processing-document.md index b51bfd34..c75f4d25 100644 --- a/docs/word/how-to-extract-styles-from-a-word-processing-document.md +++ b/docs/word/how-to-extract-styles-from-a-word-processing-document.md @@ -20,7 +20,7 @@ ms.localizationpriority: medium This topic shows how to use the classes in the Open XML SDK for Office to programmatically extract the styles or stylesWithEffects part from a word processing document to an -[XDocument](https://msdn.microsoft.com/library/Bb345449(v=VS.100).aspx) +[XDocument](/dotnet/api/system.xml.linq.xdocument) instance. It contains an example **ExtractStylesPart** method to illustrate this task. @@ -31,15 +31,14 @@ illustrate this task. ## ExtractStylesPart Method You can use the **ExtractStylesPart** sample method to retrieve an **XDocument** instance that contains the styles or -stylesWithEffects part for a Microsoft Word 2010 or Microsoft Word 2013 -document. Be aware that in a document created in Word 2010, there will -only be a single styles part; Word 2013 adds a second stylesWithEffects -part. To provide for "round-tripping" a document from Word 2013 to Word -2010 and back, Word 2013 maintains both the original styles part and the +stylesWithEffects part for a Microsoft Word document. Be aware that in a document created in Word 2010, there will +only be a single styles part; Word 2013+ adds a second stylesWithEffects +part. To provide for "round-tripping" a document from Word 2013+ to Word +2010 and back, Word 2013+ maintains both the original styles part and the new styles part. (The Office Open XML File Formats specification requires that Microsoft Word ignore any parts that it does not recognize; Word 2010 does not notice the stylesWithEffects part that -Word 2013 adds to the document.) You (and your application) must +Word 2013+ adds to the document.) You (and your application) must interpret the results of retrieving the styles or stylesWithEffects part. @@ -47,7 +46,7 @@ The **ExtractStylesPart** procedure accepts a two parameters: the first parameter contains a string indicating the path of the file from which you want to extract styles, and the second indicates whether you want to retrieve the styles part, or the newer stylesWithEffects part -(basically, you must call this procedure two times for Word 2013 +(basically, you must call this procedure two times for Word 2013+ documents, retrieving each the part). The procedure returns an **XDocument** instance that contains the complete styles or stylesWithEffects part that you requested, with all the style information for the document (or a null reference, if the part you @@ -139,9 +138,9 @@ The code starts by creating a variable named **styles** that the method returns *** -The code continues by opening the document by using the [Open](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.open.aspx) method and indicating that the +The code continues by opening the document by using the [Open](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) method and indicating that the document should be open for read-only access (the final false -parameter). Given the open document, the code uses the [MainDocumentPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.maindocumentpart.aspx) property to navigate to +parameter). Given the open document, the code uses the [MainDocumentPart](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.maindocumentpart) property to navigate to the main document part, and then prepares a variable named **stylesPart** to hold a reference to the styles part. ### [C#](#tab/cs-3) @@ -212,11 +211,11 @@ of the **docPart** variable, and stores it in the If the requested styles part exists, the code must return the contents of the part in an **XDocument** instance. Each -part provides a [GetStream](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.openxmlpart.getstream.aspx) method, which returns a Stream. +part provides a [GetStream](/dotnet/api/documentformat.openxml.packaging.openxmlpart.getstream) method, which returns a Stream. The code passes the Stream instance to the -[XmlNodeReader.Create](https://msdn.microsoft.com/library/ay7fxzht(v=VS.100).aspx) +[XmlNodeReader.Create](/dotnet/api/system.xml.xmlreader.create) method, and then calls the -[XDocument.Load](https://msdn.microsoft.com/library/bb356384.aspx) +[XDocument.Load](/dotnet/api/system.xml.linq.xdocument.load) method, passing the **XmlNodeReader** as a parameter. diff --git a/docs/word/how-to-insert-a-comment-into-a-word-processing-document.md b/docs/word/how-to-insert-a-comment-into-a-word-processing-document.md index 08cf317f..db3ebbe7 100644 --- a/docs/word/how-to-insert-a-comment-into-a-word-processing-document.md +++ b/docs/word/how-to-insert-a-comment-into-a-word-processing-document.md @@ -24,10 +24,10 @@ word processing document. -------------------------------------------------------------------------------- ## Open the Existing Document for Editing -To open an existing document, instantiate the [WordprocessingDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.aspx) class as shown in +To open an existing document, instantiate the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) class as shown in the following **using** statement. In the same statement, open the word processing file at the specified *filepath* by -using the [Open(String, Boolean)](https://msdn.microsoft.com/library/office/cc562234.aspx) method, with the +using the [Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) method, with the Boolean parameter set to **true** to enable editing in the document. @@ -62,14 +62,14 @@ object that is created or named in the **using** statement, in this case *docume ## How the Sample Code Works After you open the document, you can find the first paragraph to attach a comment. The code finds the first paragraph by calling the -[First](https://msdn.microsoft.com/library/system.linq.enumerable.first.aspx) +[First](/dotnet/api/system.linq.enumerable.first) extension method on all the descendant elements of the document element -that are of type [Paragraph](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.paragraph.aspx). The **First** method is a member +that are of type [Paragraph](/dotnet/api/documentformat.openxml.wordprocessing.paragraph). The **First** method is a member of the -[System.Linq.Enumerable](https://msdn.microsoft.com/library/system.linq.enumerable.aspx) +[System.Linq.Enumerable](/dotnet/api/system.linq.enumerable) class. The **System.Linq.Enumerable** class provides extension methods for objects that implement the -[System.Collections.Generic.IEnumerable](https://msdn.microsoft.com/library/9eekhta0.aspx) +[System.Collections.Generic.IEnumerable](/dotnet/api/system.collections.generic.ienumerable-1) interface. ### [C#](#tab/cs-1) @@ -88,17 +88,17 @@ interface. *** -The code first determines whether a [WordprocessingCommentsPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingcommentspart.aspx) part exists. To -do this, call the [MainDocumentPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.maindocumentpart.aspx) generic method, **GetPartsCountOfType**, and specify a kind of **WordprocessingCommentsPart**. +The code first determines whether a [WordprocessingCommentsPart](/dotnet/api/documentformat.openxml.packaging.wordprocessingcommentspart) part exists. To +do this, call the [MainDocumentPart](/dotnet/api/documentformat.openxml.packaging.maindocumentpart) generic method, **GetPartsCountOfType**, and specify a kind of **WordprocessingCommentsPart**. If a **WordprocessingCommentsPart** part exists, the code obtains a new **Id** value for -the [Comment](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.comment.aspx) object that it will add to the -existing **WordprocessingCommentsPart** [Comments](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.comments.aspx) collection object. It does this by +the [Comment](/dotnet/api/documentformat.openxml.wordprocessing.comment) object that it will add to the +existing **WordprocessingCommentsPart** [Comments](/dotnet/api/documentformat.openxml.wordprocessing.comments) collection object. It does this by finding the highest **Id** attribute value given to a **Comment** in the **Comments** collection object, incrementing the value by one, and then storing that as the **Id** value.If no **WordprocessingCommentsPart** part exists, the code -creates one using the [AddNewPart\()](https://msdn.microsoft.com/library/office/cc562657.aspx) method of the [MainDocumentPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.maindocumentpart.aspx) object and then adds a +creates one using the [AddNewPart\()](/dotnet/api/documentformat.openxml.packaging.openxmlpartcontainer.addnewpart) method of the [MainDocumentPart](/dotnet/api/documentformat.openxml.packaging.maindocumentpart) object and then adds a **Comments** collection object to it. ### [C#](#tab/cs-2) @@ -193,16 +193,16 @@ comments part in a WordprocessingML document. With the **Comment** object instantiated, the code associates the **Comment** with a range in -the Wordprocessing document. [CommentRangeStart](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.commentrangestart.aspx) and [CommentRangeEnd](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.commentrangeend.aspx) objects correspond to the +the Wordprocessing document. [CommentRangeStart](/dotnet/api/documentformat.openxml.wordprocessing.commentrangestart) and [CommentRangeEnd](/dotnet/api/documentformat.openxml.wordprocessing.commentrangeend) objects correspond to the **commentRangeStart** and **commentRangeEnd** elements in the Open XML Wordprocessing schema. A **CommentRangeStart** -object is given as the argument to the [InsertBefore\(T, OpenXmlElement)](https://msdn.microsoft.com/library/office/cc863927.aspx) method -of the [Paragraph](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.paragraph.aspx) object and a **CommentRangeEnd** object is passed to the [InsertAfter\(T, OpenXmlElement)](https://msdn.microsoft.com/library/office/cc865786.aspx) method. +object is given as the argument to the [InsertBefore\(T, OpenXmlElement)](/dotnet/api/documentformat.openxml.openxmlcompositeelement.insertbefore) method +of the [Paragraph](/dotnet/api/documentformat.openxml.wordprocessing.paragraph) object and a **CommentRangeEnd** object is passed to the [InsertAfter\(T, OpenXmlElement)](/dotnet/api/documentformat.openxml.openxmlcompositeelement.insertafter) method. This creates a comment range that extends from immediately before the first character of the first paragraph in the Wordprocessing document to immediately after the last character of the first paragraph. -A [CommentReference](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.commentreference.aspx) object represents a +A [CommentReference](/dotnet/api/documentformat.openxml.wordprocessing.commentreference) object represents a **commentReference** element in the Open XML Wordprocessing schema. A commentReference links a specific comment in the **WordprocessingCommentsPart** part (the Comments.xml file in the Wordprocessing package) to a specific location in the @@ -214,7 +214,7 @@ a given comment, so the commentReference **id** attribute must match the comment **id** attribute value that it links to. In the sample, the code adds a **commentReference** element by using the API, and instantiates a **CommentReference** object, -specifying the **Id** value, and then adds it to a [Run](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.run.aspx) object. +specifying the **Id** value, and then adds it to a [Run](/dotnet/api/documentformat.openxml.wordprocessing.run) object. ### [C#](#tab/cs-4) ```csharp @@ -274,8 +274,8 @@ Following is the complete sample code in both C\# and Visual Basic. - [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) -[Language-Integrated Query (LINQ)](https://msdn.microsoft.com/library/bb397926.aspx) +[Language-Integrated Query (LINQ)](/previous-versions/bb397926(v=vs.140)) -[Extension Methods (C\# Programming Guide)](https://msdn.microsoft.com/library/bb383977.aspx) +[Extension Methods (C\# Programming Guide)](/dotnet/csharp/programming-guide/classes-and-structs/extension-methods) -[Extension Methods (Visual Basic)](https://msdn.microsoft.com/library/bb384936.aspx) +[Extension Methods (Visual Basic)](/dotnet/visual-basic/programming-guide/language-features/procedures/extension-methods) diff --git a/docs/word/how-to-insert-a-picture-into-a-word-processing-document.md b/docs/word/how-to-insert-a-picture-into-a-word-processing-document.md index 973632d4..d657ae0e 100644 --- a/docs/word/how-to-insert-a-picture-into-a-word-processing-document.md +++ b/docs/word/how-to-insert-a-picture-into-a-word-processing-document.md @@ -25,9 +25,9 @@ This topic shows how to use the classes in the Open XML SDK for Office to progra ## Opening an Existing Document for Editing -To open an existing document, instantiate the [WordprocessingDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.aspx) class as shown in +To open an existing document, instantiate the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) class as shown in the following **using** statement. In the same -statement, open the word processing file at the specified **filepath** by using the [Open(String, Boolean)](https://msdn.microsoft.com/library/office/cc562234.aspx) method, with the +statement, open the word processing file at the specified **filepath** by using the [Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) method, with the Boolean parameter set to **true** in order to enable editing the document. @@ -64,8 +64,7 @@ long as you use **using**. -------------------------------------------------------------------------------- ## The XML Representation of the Graphic Object -The following text from the [ISO/IEC -29500](https://www.iso.org/standard/71691.html) specification +The following text from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the Graphic Object Data element. > This element specifies the reference to a graphic object within the @@ -76,7 +75,7 @@ introduces the Graphic Object Data element. > generating application that supports the OOXML framework will have the > ability to render the graphical object. *end note*] > -> © ISO/IEC29500: 2008. +> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] The following XML Schema fragment defines the contents of this element @@ -93,7 +92,7 @@ The following XML Schema fragment defines the contents of this element ## How the Sample Code Works -After you have opened the document, add the [ImagePart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.imagepart.aspx) object to the [MainDocumentPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.maindocumentpart.aspx) object by using a file +After you have opened the document, add the [ImagePart](/dotnet/api/documentformat.openxml.packaging.imagepart) object to the [MainDocumentPart](/dotnet/api/documentformat.openxml.packaging.maindocumentpart) object by using a file stream as shown in the following code segment. ### [C#](#tab/cs-1) @@ -120,7 +119,7 @@ stream as shown in the following code segment. To add the image to the body, first define the reference of the image. -Then, append the reference to the body. The element should be in a [Run](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.run.aspx). +Then, append the reference to the body. The element should be in a [Run](/dotnet/api/documentformat.openxml.wordprocessing.run). ### [C#](#tab/cs-2) ```csharp diff --git a/docs/word/how-to-insert-a-table-into-a-word-processing-document.md b/docs/word/how-to-insert-a-table-into-a-word-processing-document.md index c52f5082..cc99b319 100644 --- a/docs/word/how-to-insert-a-table-into-a-word-processing-document.md +++ b/docs/word/how-to-insert-a-table-into-a-word-processing-document.md @@ -112,10 +112,10 @@ table row using the **tr** element. ## How the Sample Code Works -In sample code, after you open the document in the **using** statement, you create a new [Table](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.table.aspx) object. Then you create a [TableProperties](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.tableproperties.aspx) object and specify its +In sample code, after you open the document in the **using** statement, you create a new [Table](/dotnet/api/documentformat.openxml.wordprocessing.table) object. Then you create a [TableProperties](/dotnet/api/documentformat.openxml.wordprocessing.tableproperties) object and specify its border information. The **TableProperties** -class contains an overloaded constructor [TableProperties()](https://msdn.microsoft.com/library/office/cc882762.aspx) that takes a **params** array of type [OpenXmlElement](https://msdn.microsoft.com/library/office/documentformat.openxml.openxmlelement.aspx). The code uses this -constructor to instantiate a **TableProperties** object with [BorderType](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.bordertype.aspx) objects for each border, +class contains an overloaded constructor [TableProperties()](/dotnet/api/documentformat.openxml.wordprocessing.tableproperties.-ctor) that takes a **params** array of type [OpenXmlElement](/dotnet/api/documentformat.openxml.openxmlelement). The code uses this +constructor to instantiate a **TableProperties** object with [BorderType](/dotnet/api/documentformat.openxml.wordprocessing.bordertype) objects for each border, instantiating each **BorderType** and specifying its value using object initializers. After it has been instantiated, append the **TableProperties** @@ -163,20 +163,20 @@ object to the table. The code creates a table row. This section of the code makes extensive -use of the overloaded [Append\[\])](https://msdn.microsoft.com/library/office/cc801361.aspx) methods, which classes derived +use of the overloaded [Append\[\])](/dotnet/api/documentformat.openxml.openxmlelement.append) methods, which classes derived from **OpenXmlElement** inherit. The **Append** methods provide a way to either append a single element or to append a portion of an XML tree, to the end of the list of child elements under a given parent element. Next, the code -creates a [TableCell](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.tablecell.aspx) object, which represents an +creates a [TableCell](/dotnet/api/documentformat.openxml.wordprocessing.tablecell) object, which represents an individual table cell, and specifies the width property of the table -cell using a [TableCellProperties](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.tablecellproperties.aspx) object, and the cell -content ("Hello, World!") using a [Text](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.text.aspx) object. In the Open XML Wordprocessing +cell using a [TableCellProperties](/dotnet/api/documentformat.openxml.wordprocessing.tablecellproperties) object, and the cell +content ("Hello, World!") using a [Text](/dotnet/api/documentformat.openxml.wordprocessing.text) object. In the Open XML Wordprocessing schema, a paragraph element (**\**) contains run elements (**\**) which, in turn, contain text elements (**\**). To -insert text within a table cell using the API, you must create a [Paragraph](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.paragraph.aspx) object that contains a **Run** object that contains a **Text** object that contains the text you want to +insert text within a table cell using the API, you must create a [Paragraph](/dotnet/api/documentformat.openxml.wordprocessing.paragraph) object that contains a **Run** object that contains a **Text** object that contains the text you want to insert in the cell. You then append the **Paragraph** object to the **TableCell** object. This creates the proper XML -structure for inserting text into a cell. The **TableCell** is then appended to the [TableRow](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.tablerow.aspx) object. +structure for inserting text into a cell. The **TableCell** is then appended to the [TableRow](/dotnet/api/documentformat.openxml.wordprocessing.tablerow) object. ### [C#](#tab/cs-2) ```csharp @@ -217,9 +217,9 @@ structure for inserting text into a cell. The **TableCell** is then appended to The code then creates a second table cell. The final section of code -creates another table cell using the overloaded **TableCell** constructor [TableCell(String)](https://msdn.microsoft.com/library/office/cc803944.aspx) that takes the [OuterXml](https://msdn.microsoft.com/library/office/documentformat.openxml.openxmlelement.outerxml.aspx) property of an existing **TableCell** object as its only argument. After +creates another table cell using the overloaded **TableCell** constructor [TableCell(String)](/dotnet/api/documentformat.openxml.wordprocessing.tablecell.-ctor) that takes the [OuterXml](/dotnet/api/documentformat.openxml.openxmlelement.outerxml) property of an existing **TableCell** object as its only argument. After creating the second table cell, the code appends the **TableCell** to the **TableRow**, appends the **TableRow** to the **Table**, and the **Table** -to the [Document](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.document.aspx) object. +to the [Document](/dotnet/api/documentformat.openxml.wordprocessing.document) object. ### [C#](#tab/cs-3) ```csharp @@ -298,6 +298,6 @@ Following is the complete sample code in both C\# and Visual Basic. - [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) -[Object Initializers: Named and Anonymous Types (Visual Basic .NET)](https://msdn.microsoft.com/library/bb385125.aspx) +[Object Initializers: Named and Anonymous Types (Visual Basic .NET)](/dotnet/visual-basic/programming-guide/language-features/objects-and-classes/object-initializers-named-and-anonymous-types) -[Object and Collection Initializers (C\# Programming Guide)](https://msdn.microsoft.com/library/bb384062.aspx) +[Object and Collection Initializers (C\# Programming Guide)](/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers) diff --git a/docs/word/how-to-open-a-word-processing-document-for-read-only-access.md b/docs/word/how-to-open-a-word-processing-document-for-read-only-access.md index ba37a99c..f118cf78 100644 --- a/docs/word/how-to-open-a-word-processing-document-for-read-only-access.md +++ b/docs/word/how-to-open-a-word-processing-document-for-read-only-access.md @@ -33,7 +33,7 @@ programmatically open a read-only word processing document. -------------------------------------------------------------------------------- ## Create a WordprocessingDocument Object -In the Open XML SDK, the [WordprocessingDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.aspx) class represents a +In the Open XML SDK, the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) class represents a Word document package. To work with a Word document, first create an instance of the **WordprocessingDocument** class from the document, and then work with that instance. Once you @@ -51,10 +51,10 @@ editable are listed in the following table. Open Method|Class Library Reference Topic|Description --|--|-- -Open(String, Boolean)|[Open(String, Boolean)](https://msdn.microsoft.com/library/office/cc562234.aspx) |Create an instance of the **WordprocessingDocument** class from the specified file. -Open(Stream, Boolean)|[Open(Stream, Boolean)](https://msdn.microsoft.com/library/office/cc536138.aspx) |Create an instance of the **WordprocessingDocument** class from the specified IO stream. -Open(String, Boolean, OpenSettings)|[Open(String, Boolean, OpenSettings)](https://msdn.microsoft.com/library/office/ee857385.aspx) |Create an instance of the **WordprocessingDocument** class from the specified file. -Open(Stream, Boolean, OpenSettings)|[Open(Stream, Boolean, OpenSettings)](https://msdn.microsoft.com/library/office/ee863626.aspx) |Create an instance of the **WordprocessingDocument** class from the specified I/O stream. +Open(String, Boolean)|[Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) |Create an instance of the **WordprocessingDocument** class from the specified file. +Open(Stream, Boolean)|[Open(Stream, Boolean)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) |Create an instance of the **WordprocessingDocument** class from the specified IO stream. +Open(String, Boolean, OpenSettings)|[Open(String, Boolean, OpenSettings)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) |Create an instance of the **WordprocessingDocument** class from the specified file. +Open(Stream, Boolean, OpenSettings)|[Open(Stream, Boolean, OpenSettings)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) |Create an instance of the **WordprocessingDocument** class from the specified I/O stream. The table above lists only those **Open** methods that accept a Boolean value as the second parameter to specify diff --git a/docs/word/how-to-open-a-word-processing-document-from-a-stream.md b/docs/word/how-to-open-a-word-processing-document-from-a-stream.md index fe04daed..bbc88237 100644 --- a/docs/word/how-to-open-a-word-processing-document-from-a-stream.md +++ b/docs/word/how-to-open-a-word-processing-document-from-a-stream.md @@ -37,7 +37,7 @@ adds text to the document behind the stream using the Open XML SDK. ## Creating a WordprocessingDocument Object -In the Open XML SDK, the [WordprocessingDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.aspx) class represents a +In the Open XML SDK, the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) class represents a Word document package. To work with a Word document, first create an instance of the **WordprocessingDocument** class from the document, and then work with that instance. When you @@ -50,7 +50,7 @@ a Word document, the text in the main document part is represented in the package as XML using **WordprocessingML** markup. -To create the class instance from the document call the [Open(Stream, Boolean)](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.aspx) method. Several **Open** methods are provided, each with a different +To create the class instance from the document call the [Open(Stream, Boolean)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) method. Several **Open** methods are provided, each with a different signature. The sample code in this topic uses the **Open** method with a signature that requires two parameters. The first parameter takes a handle to the stream from which you want to open the document. The second parameter is either **true** or **false** and diff --git a/docs/word/how-to-open-and-add-text-to-a-word-processing-document.md b/docs/word/how-to-open-and-add-text-to-a-word-processing-document.md index 83314f48..eb2dd7c6 100644 --- a/docs/word/how-to-open-and-add-text-to-a-word-processing-document.md +++ b/docs/word/how-to-open-and-add-text-to-a-word-processing-document.md @@ -34,7 +34,7 @@ elements, and their corresponding Open XML SDK classes. -------------------------------------------------------------------------------- ## Create a WordprocessingDocument Object -In the Open XML SDK, the [WordprocessingDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.aspx) class represents a +In the Open XML SDK, the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) class represents a Word document package. To open and work with a Word document, create an instance of the **WordprocessingDocument** class from the document. When you create the instance from the document, @@ -43,7 +43,7 @@ text of the document. The text in the main document part is represented in the package as XML using **WordprocessingML** markup. To create the class instance from the document you call one of the **Open** methods. Several are provided, each with a -different signature. The sample code in this topic uses the [Open(String, Boolean)](https://msdn.microsoft.com/library/office/cc562234.aspx) method with a +different signature. The sample code in this topic uses the [Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) method with a signature that requires two parameters. The first parameter takes a full path string that represents the document to open. The second parameter is either **true** or **false** and represents whether you want the file to diff --git a/docs/word/how-to-remove-hidden-text-from-a-word-processing-document.md b/docs/word/how-to-remove-hidden-text-from-a-word-processing-document.md index 4da35b80..38b3c32e 100644 --- a/docs/word/how-to-remove-hidden-text-from-a-word-processing-document.md +++ b/docs/word/how-to-remove-hidden-text-from-a-word-processing-document.md @@ -74,7 +74,7 @@ code example shows the **WordprocessingML** markup for a document that contains the text "Example text." ```xml - + @@ -87,17 +87,17 @@ markup for a document that contains the text "Example text." 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](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.aspx) +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. WordprocessingML Element|Open XML SDK Class|Description --|--|-- -document|[Document](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.document.aspx) |The root element for the main document part. -body|[Body](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.body.aspx) |The container for the block level structures such as paragraphs, tables, annotations and others specified in the [ISO/IEC 29500](https://www.iso.org/standard/71691.html) specification. -p|[Paragraph](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.paragraph.aspx) |A paragraph. -r|[Run](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.run.aspx) |A run. -t|[Text](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.text.aspx) |A range of text. +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. --------------------------------------------------------------------------------- @@ -113,7 +113,7 @@ direct formatting, setting it to **true** or **false** sets the absolute state of the resulting property. -The following information from the [ISO/IEC 29500](https://www.iso.org/standard/71691.html) specification +The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the **vanish** element. > **vanish (Hidden Text)** @@ -144,7 +144,7 @@ introduces the **vanish** element. > of this run, so the contents of this run will be hidden when the > document contents are displayed. *end example*] > -> © ISO/IEC29500: 2008. +> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] The following XML schema segment defines the contents of this element. diff --git a/docs/word/how-to-remove-the-headers-and-footers-from-a-word-processing-document.md b/docs/word/how-to-remove-the-headers-and-footers-from-a-word-processing-document.md index df2a3ed3..254bd21e 100644 --- a/docs/word/how-to-remove-the-headers-and-footers-from-a-word-processing-document.md +++ b/docs/word/how-to-remove-the-headers-and-footers-from-a-word-processing-document.md @@ -72,9 +72,9 @@ in the following code example. The **RemoveHeadersAndFooters** method works with the document you specify, deleting all of the header and footer parts and references to those parts. The code starts by opening the -document, using the [Open](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.open.aspx) method and indicating that the +document, using the [Open](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) method and indicating that the document should be opened for read/write access (the final true -parameter). Given the open document, the code uses the [MainDocumentPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.maindocumentpart.aspx) property to navigate to +parameter). Given the open document, the code uses the [MainDocumentPart](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.maindocumentpart) property to navigate to the main document, storing the reference in a variable named **docPart**. ### [C#](#tab/cs-2) @@ -103,11 +103,11 @@ the main document, storing the reference in a variable named **docPart**. Given a reference to the document part, the code next determines if it has any work to do─that is, if the document contains any headers or -footers. To decide, the code calls the **Count** method of both the [HeaderParts](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.maindocumentpart.headerparts.aspx) and [FooterParts](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.maindocumentpart.footerparts.aspx) properties of the document +footers. To decide, the code calls the **Count** method of both the [HeaderParts](/dotnet/api/documentformat.openxml.packaging.maindocumentpart.headerparts) and [FooterParts](/dotnet/api/documentformat.openxml.packaging.maindocumentpart.footerparts) properties of the document part, and if either returns a value greater than 0, the code continues. Be aware that the **HeaderParts** and **FooterParts** properties each return an -[IEnumerable](https://msdn.microsoft.com/library/9eekhta0.aspx) of -[HeaderPart](https://msdn.microsoft.com/library/9eekhta0.aspx) or [FooterPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.footerpart.aspx) objects, respectively. +[IEnumerable](/dotnet/api/system.collections.generic.ienumerable-1) of +[HeaderPart](/dotnet/api/system.collections.generic.ienumerable-1) or [FooterPart](/dotnet/api/documentformat.openxml.packaging.footerpart) objects, respectively. ### [C#](#tab/cs-3) ```csharp @@ -142,7 +142,7 @@ Be aware that the **HeaderParts** and **FooterParts** properties each return an Given a collection of references to header and footer parts, you could write code to delete each one individually, but that is not necessary -because of the Open XML SDK. Instead, you can call the [DeleteParts\](https://msdn.microsoft.com/library/office/cc562335.aspx) method, passing in the +because of the Open XML SDK. Instead, you can call the [DeleteParts\](/dotnet/api/documentformat.openxml.packaging.openxmlpartcontainer.deleteparts) method, passing in the collection of parts to be deleted─this simple method provides a shortcut for deleting a collection of parts. Therefore, the following few lines of code take the place of the loop that you would otherwise have to @@ -201,10 +201,10 @@ shown in the section that follows the following code example. To remove the stranded references, the code first retrieves a collection of HeaderReference elements, converts the collection to a List, and then -loops through the collection, calling the [Remove](https://msdn.microsoft.com/library/office/documentformat.openxml.openxmlelement.remove.aspx) method for each element found. Note +loops through the collection, calling the [Remove](/dotnet/api/documentformat.openxml.openxmlelement.remove) method for each element found. Note that the code converts the **IEnumerable** -returned by the [Descendants](https://msdn.microsoft.com/library/office/documentformat.openxml.openxmlelement.descendants.aspx) method into a List so that it -can delete items from the list, and that the [HeaderReference](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.headerreference.aspx) type that is provided by +returned by the [Descendants](/dotnet/api/documentformat.openxml.openxmlelement.descendants) method into a List so that it +can delete items from the list, and that the [HeaderReference](/dotnet/api/documentformat.openxml.wordprocessing.headerreference) type that is provided by the Open XML SDK makes it easy to refer to elements of type **HeaderReference** in the XML content. (Without that additional help, you would have to work with the details of the XML content directly.) Once it has removed all the headers, the code repeats diff --git a/docs/word/how-to-replace-the-header-in-a-word-processing-document.md b/docs/word/how-to-replace-the-header-in-a-word-processing-document.md index 10a1b118..0cf9c24e 100644 --- a/docs/word/how-to-replace-the-header-in-a-word-processing-document.md +++ b/docs/word/how-to-replace-the-header-in-a-word-processing-document.md @@ -30,7 +30,7 @@ file and create another header part. You are also going to delete the reference to the existing header and create a reference to the new header. Therefore it is useful to familarize yourself with headers and the header reference element. The following information from the -[ISO/IEC 29500](https://www.iso.org/standard/71691.html) +[!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the header reference element. ## headerReference (Header Reference) @@ -77,7 +77,7 @@ from the document part with a unique relationship ID, as shown in the following packaging markup: ```xml - + @@ -104,7 +104,7 @@ The resulting section shall use the header part with relationship id relationship id **rId2** for all subsequent even pages, and the header part with relationship id **rId5** for all subsequent odd pages. *end example*] -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ## Sample Code diff --git a/docs/word/how-to-replace-the-styles-parts-in-a-word-processing-document.md b/docs/word/how-to-replace-the-styles-parts-in-a-word-processing-document.md index f36a3699..06511740 100644 --- a/docs/word/how-to-replace-the-styles-parts-in-a-word-processing-document.md +++ b/docs/word/how-to-replace-the-styles-parts-in-a-word-processing-document.md @@ -40,7 +40,7 @@ in .zip files is called the Open Packaging Conventions. For more information about the Open Packaging Conventions, see [ISO/IEC 29500-2](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.md?csnumber=51459). Styles are stored in dedicated parts within a word processing document -package. An Microsoft Word 2010 document contains a single styles part. +package. A Microsoft Word 2010 document contains a single styles part. Microsoft Word 2013 adds a second stylesWithEffects part. The following image from the Document Explorer in the Open XML SDK Productivity Tool for Microsoft Office shows the document parts in a sample Word 2013 @@ -49,12 +49,12 @@ document that contains styles. Figure 1. Styles parts in a word processing document ![Styles parts in a word processing document.](../media/OpenXmlCon_HowToReplaceStyles_Fig1.gif) -In order to provide for "round-tripping" a document from Word 2013 to -Word 2010 and back, Word 2013 maintains both the original styles part +In order to provide for "round-tripping" a document from Word 2013+ to +Word 2010 and back, Word 2013+ maintains both the original styles part and the new styles part. (The Office Open XML File Formats specification requires that Microsoft Word ignore any parts that it does not recognize; Word 2010 does not notice the stylesWithEffects part that -Word 2013 adds to the document.) +Word 2013+ adds to the document.) The code example provided in this topic can be used to replace these styles parts. @@ -123,7 +123,7 @@ stylesWithEffects part second, and relies on two supporting methods to do most of the work. The **ExtractStylesPart** method has the job of extracting the content of the styles or stylesWithEffects part, and placing it in an -[XDocument](https://msdn.microsoft.com/library/Bb345449(v=VS.100).aspx) +[XDocument](/dotnet/api/system.xml.linq.xdocument) object. The **ReplaceStylesPart** method takes the object created by **ExtractStylesPart** and uses its content to replace the styles or stylesWithEffects part in the @@ -158,7 +158,7 @@ stylesWithEffects part. ### [C#](#tab/cs-3) ```csharp // Extract and replace the stylesWithEffects part. To fully support - // round-tripping from Word 2013 to Word 2010, you should + // round-tripping from Word 2013+ to Word 2010, you should // replace this part, as well. node = ExtractStylesPart(fromDoc); if (node != null) @@ -169,7 +169,7 @@ stylesWithEffects part. ### [Visual Basic](#tab/vb-3) ```vb ' Extract and replace the stylesWithEffects part. To fully support - ' round-tripping from Word 2013 to Word 2010, you should + ' round-tripping from Word 2013+ to Word 2010, you should ' replace this part, as well. node = ExtractStylesPart(fromDoc, True) If node IsNot Nothing Then @@ -188,7 +188,7 @@ following section explains the **ReplaceStylesPart** method. The **ReplaceStylesPart** method can be used to replace the styles or styleWithEffects part in a document, given an **XDocument** instance that contains the same -part for a Word 2010 or Word 2013 document (as shown in the sample code +part for a Word 2010 or Word 2013+ document (as shown in the sample code earlier in this topic, the **ExtractStylesPart** method can be used to obtain that instance). The **ReplaceStylesPart** method accepts three parameters: the first parameter contains a string @@ -198,7 +198,7 @@ contains the styles or stylesWithEffect part from another word processing document, and the third indicates whether you want to replace the styles part, or the stylesWithEffects part (as shown in the sample code earlier in this topic, you will need to call this procedure twice -for Word 2013 documents, replacing each part with the corresponding part +for Word 2013+ documents, replacing each part with the corresponding part from a source document). ### [C#](#tab/cs-4) @@ -224,9 +224,9 @@ The **ReplaceStylesPart** method examines the document you specify, looking for the styles or stylesWithEffects part. If the requested part exists, the method saves the supplied **XDocument** into the selected part. -The code starts by opening the document by using the **[Open](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.open.aspx)** method and indicating that the +The code starts by opening the document by using the **[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). Given the open document, the code -uses the **[MainDocumentPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.maindocumentpart.aspx)** property to navigate to +uses the **[MainDocumentPart](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.maindocumentpart)** property to navigate to the main document part, and then prepares a variable named **stylesPart** to hold a reference to the styles part. ### [C#](#tab/cs-5) @@ -292,12 +292,12 @@ requested styles part, and stores it in the **stylesPart** variable. Assuming that the requested part exists, the code must save the entire contents of the **XDocument** passed to the -method to the part. Each part provides a **[GetStream](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.openxmlpart.getstream.aspx)** method, which returns a Stream. +method to the part. Each part provides a **[GetStream](/dotnet/api/documentformat.openxml.packaging.openxmlpart.getstream)** method, which returns a Stream. The code passes the Stream instance to the constructor of the -[StreamWriter](https://msdn.microsoft.com/library/wtbhzte9(v=VS.100).aspx) +[StreamWriter](/dotnet/api/system.io.streamwriter.-ctor) class, creating a stream writer around the stream of the part. Finally, the code calls the -[Save](https://msdn.microsoft.com/library/cc838476.aspx) method of +[Save](/dotnet/api/system.xml.linq.xdocument.save) method of the XDocument, saving its contents into the styles part. ### [C#](#tab/cs-7) diff --git a/docs/word/how-to-retrieve-application-property-values-from-a-word-processing-document.md b/docs/word/how-to-retrieve-application-property-values-from-a-word-processing-document.md index 5bbd171e..c5448c1d 100644 --- a/docs/word/how-to-retrieve-application-property-values-from-a-word-processing-document.md +++ b/docs/word/how-to-retrieve-application-property-values-from-a-word-processing-document.md @@ -18,7 +18,7 @@ ms.localizationpriority: medium # Retrieve application property values from a word processing document -This topic shows how to use the classes in the Open XML SDK for Office to programmatically retrieve an application property from a Microsoft Word 2013 document, without loading the document into Word. It contains example code to illustrate this task. +This topic shows how to use the classes in the Open XML SDK for Office to programmatically retrieve an application property from a Microsoft Word document, without loading the document into Word. It contains example code to illustrate this task. diff --git a/docs/word/how-to-retrieve-comments-from-a-word-processing-document.md b/docs/word/how-to-retrieve-comments-from-a-word-processing-document.md index 930a17ea..2d52a5b9 100644 --- a/docs/word/how-to-retrieve-comments-from-a-word-processing-document.md +++ b/docs/word/how-to-retrieve-comments-from-a-word-processing-document.md @@ -24,9 +24,9 @@ part in a word processing document. -------------------------------------------------------------------------------- ## Open the Existing Document for Read-only Access -To open an existing document, instantiate the [WordprocessingDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.aspx) class as shown in +To open an existing document, instantiate the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) class as shown in the following **using** statement. In the same -statement, open the word processing file at the specified **fileName** by using the [Open(String, Boolean)](https://msdn.microsoft.com/library/office/cc562234.aspx) method. To open the +statement, open the word processing file at the specified **fileName** by using the [Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) method. To open the file for editing the Boolean parameter is set to **true**. In this example you just need to read the file; therefore, you can open the file for read-only access by setting the Boolean parameter to **false**. @@ -62,8 +62,7 @@ The **comments** and **comment** elements are crucial to working with comments in a word processing file. It is important in this code example to familiarize yourself with those elements. -The following information from the [ISO/IEC -29500](https://www.iso.org/standard/71691.html) specification +The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the comments element. > **comments (Comments Collection)** @@ -83,7 +82,7 @@ introduces the comments element. ``` -> © ISO/IEC29500: 2008. +> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] The following XML schema segment defines the contents of the comments element. @@ -98,8 +97,7 @@ element. --------------------------------------------------------------------------------- ## Comment Element -The following information from the [ISO/IEC -29500](https://www.iso.org/standard/71691.html) specification +The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the comment element. > **comment (Comment Content)** @@ -127,7 +125,7 @@ introduces the comment element. > The **comment** element specifies the presence of a single comment > within the comments part. > -> © ISO/IEC29500: 2008. +> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] The following XML schema segment defines the contents of the comment diff --git a/docs/word/how-to-set-a-custom-property-in-a-word-processing-document.md b/docs/word/how-to-set-a-custom-property-in-a-word-processing-document.md index 692f7823..928192ae 100644 --- a/docs/word/how-to-set-a-custom-property-in-a-word-processing-document.md +++ b/docs/word/how-to-set-a-custom-property-in-a-word-processing-document.md @@ -169,7 +169,7 @@ Figure 2. Custom Properties in the Advanced Properties dialog box ## How the Code Works -The **SetCustomProperty** method starts by setting up some internal variables. Next, it examines the information about the property, and creates a new [CustomDocumentProperty](https://msdn.microsoft.com/library/office/documentformat.openxml.customproperties.customdocumentproperty.aspx) based on the parameters that you have specified. The code also maintains a variable named **propSet** to indicate whether it successfully created the new property object. This code verifies the +The **SetCustomProperty** method starts by setting up some internal variables. Next, it examines the information about the property, and creates a new [CustomDocumentProperty](/dotnet/api/documentformat.openxml.customproperties.customdocumentproperty) based on the parameters that you have specified. The code also maintains a variable named **propSet** to indicate whether it successfully created the new property object. This code verifies the type of the property value, and then converts the input to the correct type, setting the appropriate property of the **CustomDocumentProperty** object. > [!NOTE] @@ -300,7 +300,7 @@ type of the property value, and then converts the input to the correct type, set *** -At this point, if the code has not thrown an exception, you can assume that the property is valid, and the code sets the [FormatId](https://msdn.microsoft.com/library/office/documentformat.openxml.customproperties.customdocumentproperty.formatid.aspx) and [Name](https://msdn.microsoft.com/library/office/documentformat.openxml.customproperties.customdocumentproperty.name.aspx) properties of the new custom property. +At this point, if the code has not thrown an exception, you can assume that the property is valid, and the code sets the [FormatId](/dotnet/api/documentformat.openxml.customproperties.customdocumentproperty.formatid) and [Name](/dotnet/api/documentformat.openxml.customproperties.customdocumentproperty.name) properties of the new custom property. ### [C#](#tab/cs-4) ```csharp @@ -323,7 +323,7 @@ At this point, if the code has not thrown an exception, you can assume that the ## Working with the Document Given the **CustomDocumentProperty** object, the code next interacts with the document that you supplied in the parameters to the **SetCustomProperty** procedure. The code starts by opening the document in read/write mode by -using the [Open](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.open.aspx) method of the [WordprocessingDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.aspx) class. The code attempts to retrieve a reference to the custom file properties part by using the [CustomFilePropertiesPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.customfilepropertiespart.aspx) property of the document. +using the [Open](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) method of the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) class. The code attempts to retrieve a reference to the custom file properties part by using the [CustomFilePropertiesPart](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.customfilepropertiespart) property of the document. ### [C#](#tab/cs-5) ```csharp @@ -370,7 +370,7 @@ If the code cannot find a custom properties part, it creates a new part, and add *** -Next, the code retrieves a reference to the [Properties](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.customfilepropertiespart.properties.aspx) property of the custom +Next, the code retrieves a reference to the [Properties](/dotnet/api/documentformat.openxml.packaging.customfilepropertiespart.properties) property of the custom properties part (that is, a reference to the properties themselves). If the code had to create a new custom properties part, you know that this reference is not null. However, for existing custom properties parts, it diff --git a/docs/word/how-to-set-the-font-for-a-text-run.md b/docs/word/how-to-set-the-font-for-a-text-run.md index 87065d56..ecdc934a 100644 --- a/docs/word/how-to-set-the-font-for-a-text-run.md +++ b/docs/word/how-to-set-the-font-for-a-text-run.md @@ -11,7 +11,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 01/16/2024 ms.localizationpriority: high --- # Set the font for a text run @@ -27,50 +27,10 @@ document programmatically. -------------------------------------------------------------------------------- -## Create a WordprocessingDocument Object -The code example opens a word processing document package by passing a -file name as an argument to one of the overloaded [Open()](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.open.aspx) methods of the [WordprocessingDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.aspx) 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 -**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 package = WordprocessingDocument.Open(fileName, true)) - { - // Insert other code here. - } -``` - -### [Visual Basic](#tab/vb-0) -```vb - ' Open a Wordprocessing document for editing. - Dim package As WordprocessingDocument = WordprocessingDocument.Open(fileName, True) - Using (package) - ' Insert other code here. - End Using -``` -*** - - -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 **package**. Because the **WordprocessingDocument** 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. - --------------------------------------------------------------------------------- ## Structure of the Run Fonts Element -The following text from the [ISO/IEC -29500](https://www.iso.org/standard/71691.html) specification can + +The following text from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification can be useful when working with **rFonts** element. This element specifies the fonts which shall be used to display the text @@ -123,110 +83,61 @@ This text run shall therefore use the Courier New font for all characters in the ASCII range, and shall use the Times New Roman font for all characters in the Complex Script range. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] -------------------------------------------------------------------------------- ## How the Sample Code Works + After opening the package file for read/write, the code creates a **RunProperties** object that contains a **RunFonts** object that has its **Ascii** property set to "Arial". **RunProperties** and **RunFonts** objects represent run properties -(\<**rPr**\>) elements and run fonts elements -(\<**rFont**\>), respectively, in the Open XML +`rPr` elements and run fonts elements +`rFont`, respectively, in the Open XML Wordprocessing schema. Use a **RunProperties** object to specify the properties of a given text run. In this case, to set the font of the run to Arial, the code creates a **RunFonts** object and then sets the **Ascii** value to "Arial". ### [C#](#tab/cs-1) -```csharp - // Use an object initializer for RunProperties and rPr. - RunProperties rPr = new RunProperties( - new RunFonts() - { - Ascii = "Arial" - }); -``` - +[!code-csharp[](../../samples/word/set_the_font_for_a_text_run/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-1) -```vb - ' Use an object initializer for RunProperties and rPr. - Dim rPr As New RunProperties(New RunFonts() With {.Ascii = "Arial"}) -``` +[!code-vb[](../../samples/word/set_the_font_for_a_text_run/vb/Program.vb#snippet1)] *** -The code then creates a [Run](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.run.aspx) object that represents the first text +The code then creates a [Run](/dotnet/api/documentformat.openxml.wordprocessing.run) object that represents the first text run of the document. The code instantiates a **Run** and sets it to the first text run of the -document. The code then adds the **RunProperties** object to the **Run** object using the [PrependChild\(T)](https://msdn.microsoft.com/library/office/cc883719.aspx) method. The **PrependChild** method adds an element as the first +document. The code then adds the **RunProperties** object to the **Run** object using the [PrependChild\(T)](/dotnet/api/documentformat.openxml.openxmlelement.prependchild) method. The **PrependChild** method adds an element as the first child element to the specified element in the in-memory XML structure. In this case, running the code sample produces an in-memory XML structure where the **RunProperties** element is added as the first child element of the **Run** element. It then saves the changes back to -the [Save(MainDocumentPart)](https://msdn.microsoft.com/library/office/cc846392.aspx) object. Calling the -**Save** method of the [WordprocessingDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.wordprocessingdocument.aspx) object commits +the [Save(MainDocumentPart)](/dotnet/api/documentformat.openxml.wordprocessing.document.save) object. Calling the +**Save** method of the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) object commits changes made to the in-memory representation of the **MainDocumentPart** part back into the XML file for the **MainDocumentPart** (the document.xml file in the Wordprocessing package). ### [C#](#tab/cs-2) -```csharp - Run r = package.MainDocumentPart.Document.Descendants().First(); - r.PrependChild(rPr); - - // Save changes to the MainDocumentPart part. - package.MainDocumentPart.Document.Save(); -``` - +[!code-csharp[](../../samples/word/set_the_font_for_a_text_run/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-2) -```vb - Dim r As Run = package.MainDocumentPart.Document.Descendants(Of Run)().First() - r.PrependChild(Of RunProperties)(rPr) - - ' Save changes to the MainDocumentPart part. - package.MainDocumentPart.Document.Save() -``` +[!code-vb[](../../samples/word/set_the_font_for_a_text_run/vb/Program.vb#snippet2)] *** -------------------------------------------------------------------------------- -## Sample Code -The following is the code you can use to change the font of the first -paragraph of a Word-processing document. For instance, you can invoke -the **SetRunFont** method in your program to -change the font in the file "myPkg9.docx" by using the following call. - -### [C#](#tab/cs-3) -```csharp - string fileName = @"C:\Users\Public\Documents\MyPkg9.docx"; - SetRunFont(fileName); -``` - -### [Visual Basic](#tab/vb-3) -```vb - Dim fileName As String = "C:\Users\Public\Documents\MyPkg9.docx" - SetRunFont(fileName) -``` -*** - - -After running the program check your file "MyPkg9.docx" to see the -changed font. > [!NOTE] -> This code example assumes that the test word processing document (MyPakg9.docx) contains at least one text run. +> This code example assumes that the test word processing document at fileName path contains at least one text run. The following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/set_the_font_for_a_text_run/cs/Program.cs)] +[!code-csharp[](../../samples/word/set_the_font_for_a_text_run/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/set_the_font_for_a_text_run/vb/Program.vb)] +[!code-vb[](../../samples/word/set_the_font_for_a_text_run/vb/Program.vb#snippet0)] -------------------------------------------------------------------------------- ## See also - [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) - -[Object Initializers: Named and Anonymous Types](https://msdn.microsoft.com/library/bb385125.aspx) - -[Object and Collection Initializers (C\# Programming Guide)](https://msdn.microsoft.com/library/bb384062.aspx) diff --git a/docs/word/how-to-validate-a-word-processing-document.md b/docs/word/how-to-validate-a-word-processing-document.md index 25acfedf..96516b88 100644 --- a/docs/word/how-to-validate-a-word-processing-document.md +++ b/docs/word/how-to-validate-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/16/2024 ms.localizationpriority: high --- # Validate a word processing document @@ -29,43 +29,11 @@ after running the validation check. The second method, **ValidateCorruptedWordDo inserting some text into the body, which causes a schema error. It then validates the Word file, in which case the method throws an exception on trying to open the corrupted file. The validation is done by using the -[Validate](https://msdn.microsoft.com/library/office/documentformat.openxml.validation.openxmlvalidator.validate.aspx) method. The code displays +[Validate](/dotnet/api/documentformat.openxml.validation.openxmlvalidator.validate) method. The code displays information about any errors that are found, in addition to the count of errors. - -------------------------------------------------------------------------------- -## Sample Code -In your main method, you can call the two methods, **ValidateWordDocument** and **ValidateCorruptedWordDocument** by using the -following example that validates a file named "Word18.docx.". - -### [C#](#tab/cs-0) -```csharp - string filepath = @"C:\Users\Public\Documents\Word18.docx"; - ValidateWordDocument(filepath); - Console.WriteLine("The file is valid so far."); - Console.WriteLine("Inserting some text into the body that would cause Schema error"); - Console.ReadKey(); - - ValidateCorruptedWordDocument(filepath); - Console.WriteLine("All done! Press a key."); - Console.ReadKey(); -``` - -### [Visual Basic](#tab/vb-0) -```vb - Dim filepath As String = "C:\Users\Public\Documents\Word18.docx" - ValidateWordDocument(filepath) - Console.WriteLine("The file is valid so far.") - Console.WriteLine("Inserting some text into the body that would cause Schema error") - Console.ReadKey() - - ValidateCorruptedWordDocument(filepath) - Console.WriteLine("All done! Press a key.") - Console.ReadKey() -``` -*** - > [!Important] > Notice that you cannot run the code twice after corrupting the file in the first run. You have to start with a new Word file. @@ -73,10 +41,10 @@ following example that validates a file named "Word18.docx.". Following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/validate/cs/Program.cs)] +[!code-csharp[](../../samples/word/validate/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/validate/vb/Program.vb)] +[!code-vb[](../../samples/word/validate/vb/Program.vb#snippet0)] -------------------------------------------------------------------------------- ## See also diff --git a/docs/word/structure-of-a-wordprocessingml-document.md b/docs/word/structure-of-a-wordprocessingml-document.md index c1312144..dfd4e6f5 100644 --- a/docs/word/structure-of-a-wordprocessingml-document.md +++ b/docs/word/structure-of-a-wordprocessingml-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/12/2024 ms.localizationpriority: high --- # Structure of a WordprocessingML document @@ -19,11 +19,11 @@ ms.localizationpriority: high This topic discusses the basic structure of a **WordprocessingML** document and reviews important Open XML SDK classes that are used most often to create **WordprocessingML** documents. -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 +The basic document structure of a **WordProcessingML** document consists of the `` and `` elements, followed by one or more block +level elements such as `

`, which +represents a paragraph. A paragraph contains one or more `` elements. The `` 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. +or more `` elements. The `` element contains a range of text. ## Important WordprocessingML Parts @@ -38,15 +38,15 @@ represents the element in the Open XML SDK API. | **Package Part** | **WordprocessingML Element** | **Open XML SDK Class** | **Description** | |---|---|---|---| -| Main Document|document | [Document](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.document.aspx) | The root element for the main document part. | -| Comments | comments | [Comments](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.comments.aspx) | The root element for the comments part. | -| Document Settings | settings | [Settings](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.settings.aspx) | The root element for the document settings part. | -| Endnotes | endnotes | [Endnotes](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.endnotes.aspx) | The root element for the endnotes part. | -| Footer | ftr | [Footer](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.footer.aspx) | The root element for the footer part. | -| Footnotes | footnotes | [Footnotes](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.footnotes.aspx) | The root element for the footnotes part. | -| Glossary Document | glossaryDocument | [GlossaryDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.glossarydocument.aspx) | The root element for the glossary document part. | -| Header | hdr | [Header](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.header.aspx) | The root element for the header part. | -| Style Definitions | styles | [Styles](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.styles.aspx) | The root element for a Style Definitions part. | +| Main Document|document | [Document](/dotnet/api/documentformat.openxml.wordprocessing.document) | The root element for the main document part. | +| Comments | comments | [Comments](/dotnet/api/documentformat.openxml.wordprocessing.comments) | The root element for the comments part. | +| Document Settings | settings | [Settings](/dotnet/api/documentformat.openxml.wordprocessing.settings) | The root element for the document settings part. | +| Endnotes | endnotes | [Endnotes](/dotnet/api/documentformat.openxml.wordprocessing.endnotes) | The root element for the endnotes part. | +| Footer | ftr | [Footer](/dotnet/api/documentformat.openxml.wordprocessing.footer) | The root element for the footer part. | +| Footnotes | footnotes | [Footnotes](/dotnet/api/documentformat.openxml.wordprocessing.footnotes) | The root element for the footnotes part. | +| Glossary Document | glossaryDocument | [GlossaryDocument](/dotnet/api/documentformat.openxml.wordprocessing.glossarydocument) | The root element for the glossary document part. | +| Header | hdr | [Header](/dotnet/api/documentformat.openxml.wordprocessing.header) | The root element for the header part. | +| Style Definitions | styles | [Styles](/dotnet/api/documentformat.openxml.wordprocessing.styles) | The root element for a Style Definitions part. | ## Minimum Document Scenario @@ -79,37 +79,37 @@ represented by the main document part. At a minimum, to create a valid **WordprocessingML** document using code, add a main document part to the document. -The following information from the [ISO/IEC 29500](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51463) +The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] introduces the WordprocessingML elements required in the main document part in order to complete the minimum document scenario. The main document story of the simplest WordprocessingML document consists of the following XML elements: -document — The root element for a WordprocessingML's main document part, +- `document` — The root element for a WordprocessingML's main document part, which defines the main document story. -body — The container for the collection of block-level structures that +- `body` — The container for the collection of block-level structures that comprise the main story. -p — A paragraph. +- `p` — A paragraph. -r — A run. +- `r` — A run. -t — A range of text. +- `t` — A range of text. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### Open XML SDK Code Example -The following code uses the Open XML SDK to create a simple **WordprocessingML** document that contains the text -"Hello, Word!" +The following code uses the Open XML SDK to create a simple **WordprocessingML** document that contains the text passed in as the second parameter ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/structure_of_a_wordprocessingml/cs/Program.cs)] +[!code-csharp[](../../samples/word/structure_of_a_wordprocessingml/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/structure_of_a_wordprocessingml/vb/Program.vb)] +[!code-vb[](../../samples/word/structure_of_a_wordprocessingml/vb/Program.vb#snippet0)] +*** ### Generated WordprocessingML @@ -128,16 +128,16 @@ The following XML code is generated in the document.xml file when you run the Open XML SDK code in the previous section. ```xml - - - - - - Hello, Word! - - - - + + + + + The text passed as the second parameter goes here + + + + ``` ## Typical Document Scenario diff --git a/docs/word/working-with-paragraphs.md b/docs/word/working-with-paragraphs.md index 758339c4..6836b843 100644 --- a/docs/word/working-with-paragraphs.md +++ b/docs/word/working-with-paragraphs.md @@ -11,35 +11,34 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 01/12/2024 ms.localizationpriority: high --- # Working with paragraphs -This topic discusses the Open XML SDK [Paragraph](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.paragraph.aspx) class and how it relates to the +This topic discusses the Open XML SDK [Paragraph](/dotnet/api/documentformat.openxml.wordprocessing.paragraph) class and how it relates to the Open XML File Format WordprocessingML schema. -------------------------------------------------------------------------------- ## Paragraphs in WordprocessingML -The following text from the [ISO/IEC -29500](https://www.iso.org/standard/71691.html) specification +The following text from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the Open XML WordprocessingML element used to represent a paragraph in a WordprocessingML document. The most basic unit of block-level content within a WordprocessingML -document, paragraphs are stored using the \ element. A paragraph +document, paragraphs are stored using the `

` element. A paragraph defines a distinct division of content that begins on a new line. A paragraph can contain three pieces of information: optional paragraph properties, inline content (typically runs), and a set of optional revision IDs used to compare the content of two documents. -A paragraph's properties are specified via the \element. Some +A paragraph's properties are specified via the `` element. Some examples of paragraph properties are alignment, border, hyphenation override, indentation, line spacing, shading, text direction, and widow/orphan control. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] The following table lists the most common Open XML SDK classes used when working with paragraphs. @@ -54,32 +53,32 @@ working with paragraphs. --------------------------------------------------------------------------------- ## Paragraph Class -The Open XML SDK [Paragraph](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.paragraph.aspx) class represents the paragraph -(\<**p**\>) element defined in the Open XML +The Open XML SDK [Paragraph](/dotnet/api/documentformat.openxml.wordprocessing.paragraph) class represents the paragraph +`

` element defined in the Open XML File Format schema for WordprocessingML documents as discussed above. Use the **Paragraph** object to manipulate -individual \<**p**\> elements in a +individual `

` elements in a WordprocessingML document. ### ParagraphProperties Class In WordprocessingML, a paragraph's properties are specified via the -paragraph properties (\<**pPr**\>) element. +paragraph properties `` element. Some examples of paragraph properties are alignment, border, hyphenation override, indentation, line spacing, shading, text direction, and -widow/orphan control. The OXML SDK [ParagraphProperties](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.paragraphproperties.aspx) class represents the -\<**pPr**\> element. +widow/orphan control. The OXML SDK [ParagraphProperties](/dotnet/api/documentformat.openxml.wordprocessing.paragraphproperties) class represents the +`` element. ### Run Class Paragraphs in a word-processing document most often contain text. In the -OXML File Format schema for WordprocessingML documents, the run (\<**r**\>) element is provided to demarcate a region of -text. The OXML SDK [Run](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.run.aspx) class represents the \<**r**\> element. +OXML File Format schema for WordprocessingML documents, the run `` element is provided to demarcate a region of +text. The OXML SDK [Run](/dotnet/api/documentformat.openxml.wordprocessing.run) class represents the `` element. ### Text Object -With the \<**r**\> element, the text (\<**t**\>) element is the container for the text that -makes up the document content. The OXML SDK [Text](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.text.aspx) class represents the \<**t**\> element. +With the `` element, the text `` element is the container for the text that +makes up the document content. The OXML SDK [Text](/dotnet/api/documentformat.openxml.wordprocessing.text) class represents the `` element. -------------------------------------------------------------------------------- diff --git a/docs/word/working-with-runs.md b/docs/word/working-with-runs.md index 5a7a927b..c9c4808b 100644 --- a/docs/word/working-with-runs.md +++ b/docs/word/working-with-runs.md @@ -11,19 +11,18 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 01/12/2024 ms.localizationpriority: high --- # Working with runs -This topic discusses the Open XML SDK **[Run](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.run.aspx)** class and how it relates to the Open +This topic discusses the Open XML SDK **[Run](/dotnet/api/documentformat.openxml.wordprocessing.run)** class and how it relates to the Open XML File Format WordprocessingML schema. --------------------------------------------------------------------------------- ## Runs in WordprocessingML -The following text from the [ISO/IEC -29500](https://www.iso.org/standard/71691.html) specification +The following text from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the Open XML WordprocessingML run element. The next level of the document hierarchy [after the paragraph] is the @@ -44,7 +43,7 @@ run properties are bold, border, character style, color, font, font size, italic, kerning, disable spelling/grammar check, shading, small caps, strikethrough, text direction, and underline. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] The following table lists the most common Open XML SDK classes used when working with runs. @@ -58,23 +57,23 @@ working with runs. --------------------------------------------------------------------------------- ## Run Class -The Open XML SDK[Run](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.run.aspx) class represents the run (\<**r**\>) element defined in the Open XML File Format -schema for WordprocessingML documents as discussed above. Use a **Run** object to manipulate an individual \<**r**\> element in a WordprocessingML document. +The Open XML SDK [Run](/dotnet/api/documentformat.openxml.wordprocessing.run) class represents the run `` element defined in the Open XML File Format +schema for WordprocessingML documents as discussed above. Use a **Run** object to manipulate an individual `` element in a WordprocessingML document. ### RunProperties Class In WordprocessingML, the properties for a run element are specified -using the run properties (\<**rPr**\>) element. +using the run properties `` element. Some examples of run properties are bold, border, character style, color, font, font size, italic, kerning, disable spelling/grammar check, shading, small caps, strikethrough, text direction, and underline. Use a -**[RunProperties](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.runproperties.aspx)** object to set the properties +**[RunProperties](/dotnet/api/documentformat.openxml.wordprocessing.runproperties)** object to set the properties for a run in a WordprocessingML document. ### Text Object -With the \<**r**\> element, the text (\<**t**\>) element is the container for the text that -makes up the document content. The OXML SDK **[Text](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.text.aspx)** class represents the \<**t**\> element. Use a **Text** object to place text in a Wordprocessing +With the `` element, the text (``) element is the container for the text that +makes up the document content. The OXML SDK **[Text](/dotnet/api/documentformat.openxml.wordprocessing.text)** class represents the `` element. Use a **Text** object to place text in a Wordprocessing document. @@ -86,10 +85,12 @@ object demarcates a region of text within the paragraph and then a **RunProperti formatting to the run. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/working_with_runs/cs/Program.cs)] +[!code-csharp[](../../samples/word/working_with_runs/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/working_with_runs/vb/Program.vb)] +[!code-vb[](../../samples/word/working_with_runs/vb/Program.vb#snippet0)] +*** + When this code is run, the following XML is written to the WordprocessingML document specified in the preceding code. diff --git a/docs/word/working-with-wordprocessingml-tables.md b/docs/word/working-with-wordprocessingml-tables.md index c59dad98..adb26b1c 100644 --- a/docs/word/working-with-wordprocessingml-tables.md +++ b/docs/word/working-with-wordprocessingml-tables.md @@ -11,24 +11,24 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 01/12/2024 ms.localizationpriority: high --- # Working with WordprocessingML tables -This topic discusses the Open XML SDK [Table](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.table.aspx) class and how it relates to the Office Open XML File Formats WordprocessingML schema. +This topic discusses the Open XML SDK [Table](/dotnet/api/documentformat.openxml.wordprocessing.table) class and how it relates to the Office Open XML File Formats WordprocessingML schema. ## Tables in WordprocessingML -The following text from the [ISO/IEC 29500](https://www.iso.org/standard/71691.html) specification introduces the Open XML WordprocessingML table element. +The following text from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the Open XML WordprocessingML table element. Another type of block-level content in WordprocessingML, A table is a set of paragraphs (and other block-level content) arranged in rows and columns. -Tables in WordprocessingML are defined via the tbl element, which is analogous to the HTML \ tag. The table element specifies the location of a table present in the document. +Tables in WordprocessingML are defined via the tbl element, which is analogous to the HTML `` tag. The table element specifies the location of a table present in the document. -A tbl element has two elements that define its properties: tblPr, which defines the set of table-wide properties (such as style and width), and tblGrid, which defines the grid layout of the table. A tbl element can also contain an arbitrary non-zero number of rows, where each row is specified with a tr element. Each tr element can contain an arbitrary non-zero number of cells, where each cell is specified with a tc element. +A `tbl` element has two elements that define its properties: `tblPr`, which defines the set of table-wide properties (such as style and width), and `tblGrid`, which defines the grid layout of the table. A `tbl` element can also contain an arbitrary non-zero number of rows, where each row is specified with a `tr` element. Each `tr` element can contain an arbitrary non-zero number of cells, where each cell is specified with a `tc` element. -© ISO/IEC29500: 2008. +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] The following table lists some of the most common Open XML SDK classes used when working with tables. @@ -43,121 +43,38 @@ The following table lists some of the most common Open XML SDK classes used when ## Open XML SDK Table Class -The Open XML SDK [Table](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.table.aspx) class represents the (\) element defined in the Open XML File Format schema for WordprocessingML documents as discussed above. Use a Tableobject to manipulate an individual table in a WordprocessingML document. +The Open XML SDK [Table](/dotnet/api/documentformat.openxml.wordprocessing.table) class represents the `` element defined in the Open XML File Format schema for WordprocessingML documents as discussed above. Use a Table object to manipulate an individual table in a WordprocessingML document. ## TableProperties Class -The Open XML SDK [TableProperties](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.tableproperties.aspx) class represents the (\) element defined in the Open XML File Format schema for WordprocessingML documents. The \ element defines table-wide properties for a table. Use a TableProperties object to set table-wide properties for a table in a WordprocessingML document. +The Open XML SDK [TableProperties](/dotnet/api/documentformat.openxml.wordprocessing.tableproperties) class represents the `` element defined in the Open XML File Format schema for WordprocessingML documents. The `` element defines table-wide properties for a table. Use a TableProperties object to set table-wide properties for a table in a WordprocessingML document. ## TableGrid Class -The Open XML SDK [TableGrid](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.tablegrid.aspx) class represents the (\) element defined in the Open XML File Format schema for WordprocessingML documents. In conjunction with grid column (\) child elements, the \ element defines the columns for a table and specifies the default width of table cells in the columns. Use a TableGrid object to define the columns in a table in a WordprocessingML document. +The Open XML SDK [TableGrid](/dotnet/api/documentformat.openxml.wordprocessing.tablegrid) class represents the `` element defined in the Open XML File Format schema for WordprocessingML documents. In conjunction with grid column `` child elements, the `` element defines the columns for a table and specifies the default width of table cells in the columns. Use a TableGrid object to define the columns in a table in a WordprocessingML document. ## GridColumn Class -The Open XML SDK [GridColumn](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.gridcolumn.aspx) class represents the grid column (\) element defined in the Open XML File Format schema for WordprocessingML documents. The \ element is a child element of the \ element and defines a single column in a table in a WordprocessingML document. Use the GridColumn class to manipulate an individual column in a WordprocessingML document. +The Open XML SDK [GridColumn](/dotnet/api/documentformat.openxml.wordprocessing.gridcolumn) class represents the grid column `` element defined in the Open XML File Format schema for WordprocessingML documents. The `` element is a child element of the `` element and defines a single column in a table in a WordprocessingML document. Use the GridColumn class to manipulate an individual column in a WordprocessingML document. ## TableRow Class -The Open XML SDK [TableRow](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.tablerow.aspx) class represents the table row (\) element defined in the Open XML File Format schema for WordprocessingML documents. The \ element defines a row in a table in a WordprocessingML document, analogous to the \ tag in HTML. A table row can also have formatting applied to it using a table row properties (\) element. The Open XML SDK [TableRowProperties](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.tablerowproperties.aspx) class represents the \ element. +The Open XML SDK [TableRow](/dotnet/api/documentformat.openxml.wordprocessing.tablerow) class represents the table row `` element defined in the Open XML File Format schema for WordprocessingML documents. The `` element defines a row in a table in a WordprocessingML document, analogous to the `` tag in HTML. A table row can also have formatting applied to it using a table row properties `` element. The Open XML SDK [TableRowProperties](/dotnet/api/documentformat.openxml.wordprocessing.tablerowproperties) class represents the `` element. ## TableCell Class -The Open XML SDK [TableCell](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.tablecell.aspx) class represents the table cell (\) element defined in the Open XML File Format schema for WordprocessingML documents. The \ element defines a cell in a table in a WordprocessingML document, analogous to the \ tag in HTML. A table cell can also have formatting applied to it using a table cell properties (\) element. The Open XML SDK [TableCellProperties](https://msdn.microsoft.com/library/office/documentformat.openxml.wordprocessing.tablecellproperties.aspx) class represents the \ element. +The Open XML SDK [TableCell](/dotnet/api/documentformat.openxml.wordprocessing.tablecell) class represents the table cell `` element defined in the Open XML File Format schema for WordprocessingML documents. The `` element defines a cell in a table in a WordprocessingML document, analogous to the `
` tag in HTML. A table cell can also have formatting applied to it using a table cell properties `` element. The Open XML SDK [TableCellProperties](/dotnet/api/documentformat.openxml.wordprocessing.tablecellproperties) class represents the `` element. ## Open XML SDK Code Example The following code inserts a table with 1 row and 3 columns into a document. -```c# -public static void InsertTableInDoc(string filepath) -{ - // Open a WordprocessingDocument for editing using the filepath. - using (WordprocessingDocument wordprocessingDocument = - WordprocessingDocument.Open(filepath, true)) - { - // Assign a reference to the existing document body. - Body body = wordprocessingDocument.MainDocumentPart.Document.Body; - - // Create a table. - Table tbl = new Table(); - - // Set the style and width for the table. - TableProperties tableProp = new TableProperties(); - TableStyle tableStyle = new TableStyle() { Val = "TableGrid" }; - - // Make the table width 100% of the page width. - TableWidth tableWidth = new TableWidth() { Width = "5000", Type = TableWidthUnitValues.Pct }; - - // Apply - tableProp.Append(tableStyle, tableWidth); - tbl.AppendChild(tableProp); - - // Add 3 columns to the table. - TableGrid tg = new TableGrid(new GridColumn(), new GridColumn(), new GridColumn()); - tbl.AppendChild(tg); - - // Create 1 row to the table. - TableRow tr1 = new TableRow(); - - // Add a cell to each column in the row. - TableCell tc1 = new TableCell(new Paragraph(new Run(new Text("1")))); - TableCell tc2 = new TableCell(new Paragraph(new Run(new Text("2")))); - TableCell tc3 = new TableCell(new Paragraph(new Run(new Text("3")))); - tr1.Append(tc1, tc2, tc3); - - // Add row to the table. - tbl.AppendChild(tr1); - - // Add the table to the document - body.AppendChild(tbl); - } -} -``` - -```VB -Public Sub InsertTableInDoc(ByVal filepath As String) - ' Open a WordprocessingDocument for editing using the filepath. - Using wordprocessingDocument As WordprocessingDocument = _ - WordprocessingDocument.Open(filepath, True) - ' Assign a reference to the existing document body. - Dim body As Body = wordprocessingDocument.MainDocumentPart.Document.Body - - ' Create a table. - Dim tbl As New Table() - - ' Set the style and width for the table. - Dim tableProp As New TableProperties() - Dim tableStyle As New TableStyle() With {.Val = "TableGrid"} - - ' Make the table width 100% of the page width. - Dim tableWidth As New TableWidth() With {.Width = "5000", .Type = TableWidthUnitValues.Pct} - - ' Apply - tableProp.Append(tableStyle, tableWidth) - tbl.AppendChild(tableProp) +### [C#](#tab/cs) +[!code-csharp[](../../samples/word/working_with_tables/cs/Program.cs#Snippet0)] - ' Add 3 columns to the table. - Dim tg As New TableGrid(New GridColumn(), New GridColumn(), New GridColumn()) - tbl.AppendChild(tg) - - ' Create 1 row to the table. - Dim tr1 As New TableRow() - - ' Add a cell to each column in the row. - Dim tc1 As New TableCell(New Paragraph(New Run(New Text("1")))) - Dim tc2 As New TableCell(New Paragraph(New Run(New Text("2")))) - Dim tc3 As New TableCell(New Paragraph(New Run(New Text("3")))) - tr1.Append(tc1, tc2, tc3) - - ' Add row to the table. - tbl.AppendChild(tr1) - - ' Add the table to the document - body.AppendChild(tbl) - End Using -End Sub -``` +### [Visual Basic](#tab/vb) +[!code-vb[](../../samples/word/working_with_tables/vb/Program.vb#Snippet0)] +*** When this code is run, the following XML is written to the WordprocessingML document specified in the preceding code. @@ -165,8 +82,7 @@ When this code is run, the following XML is written to the WordprocessingML docu - + diff --git a/samples/samples.sln b/samples/samples.sln index 42fbbf65..590ac98c 100644 --- a/samples/samples.sln +++ b/samples/samples.sln @@ -328,7 +328,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "copy_the_contents_of_an_ope EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "copy_the_contents_of_an_open_xml_package_part_to_a_part_a_dif_vb", "word\copy_the_contents_of_an_open_xml_package_part_to_a_part_a_dif\vb\copy_the_contents_of_an_open_xml_package_part_to_a_part_a_dif_vb.vbproj", "{BE95ECDD-B751-410E-B138-44B77DA0DE14}" EndProject -Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "retrieve_a_list_of_the_hidden_worksheets_vb", "spreadsheet\retrieve_a_list_of_the_hidden_worksheets\vb\retrieve_a_list_of_the_hidden_worksheets_vb.vbproj", "{72BE6D64-0AEB-4090-A6F9-B255D291BF14}" +Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "retrieve_a_list_of_the_hidden_worksheets_vb", "spreadsheet\retrieve_a_list_of_the_hidden_worksheets\vb\retrieve_a_list_of_the_hidden_worksheets_vb.vbproj", "{72BE6D64-0AEB-4090-A6F9-B255D291BF14}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "working_with_tables_cs", "word\working_with_tables\cs\working_with_tables_cs.csproj", "{A43A75AB-D6B6-4D31-99F7-6951AFEF502D}" +EndProject +Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "working_with_tables_vb", "word\working_with_tables\vb\working_with_tables_vb.vbproj", "{4EB1FCC9-E1E2-4D2A-ACF9-A3A31AA947A5}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -968,6 +972,14 @@ Global {72BE6D64-0AEB-4090-A6F9-B255D291BF14}.Debug|Any CPU.Build.0 = Debug|Any CPU {72BE6D64-0AEB-4090-A6F9-B255D291BF14}.Release|Any CPU.ActiveCfg = Release|Any CPU {72BE6D64-0AEB-4090-A6F9-B255D291BF14}.Release|Any CPU.Build.0 = Release|Any CPU + {A43A75AB-D6B6-4D31-99F7-6951AFEF502D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A43A75AB-D6B6-4D31-99F7-6951AFEF502D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A43A75AB-D6B6-4D31-99F7-6951AFEF502D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A43A75AB-D6B6-4D31-99F7-6951AFEF502D}.Release|Any CPU.Build.0 = Release|Any CPU + {4EB1FCC9-E1E2-4D2A-ACF9-A3A31AA947A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4EB1FCC9-E1E2-4D2A-ACF9-A3A31AA947A5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4EB1FCC9-E1E2-4D2A-ACF9-A3A31AA947A5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4EB1FCC9-E1E2-4D2A-ACF9-A3A31AA947A5}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -1130,6 +1142,8 @@ Global {6A9A6136-3F51-4FCA-B2CA-82AB69160895} = {D207D3D7-FD4D-4FD4-A7D0-79A82086FB6F} {BE95ECDD-B751-410E-B138-44B77DA0DE14} = {D207D3D7-FD4D-4FD4-A7D0-79A82086FB6F} {72BE6D64-0AEB-4090-A6F9-B255D291BF14} = {7ACDC26B-C774-4004-8553-87E862D1E71F} + {A43A75AB-D6B6-4D31-99F7-6951AFEF502D} = {D207D3D7-FD4D-4FD4-A7D0-79A82086FB6F} + {4EB1FCC9-E1E2-4D2A-ACF9-A3A31AA947A5} = {D207D3D7-FD4D-4FD4-A7D0-79A82086FB6F} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {721B3030-08D7-4412-9087-D1CFBB3F5046} diff --git a/samples/word/insert_table_in_doc/cs/Program.cs b/samples/word/insert_table_in_doc/cs/Program.cs new file mode 100644 index 00000000..cfa38a01 --- /dev/null +++ b/samples/word/insert_table_in_doc/cs/Program.cs @@ -0,0 +1,68 @@ +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; +using System; + +// +static string InsertTableInDoc(string filepath) +{ + // Open a WordprocessingDocument for editing using the filepath. + using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filepath, true)) + { + // Assign a reference to the existing document body or add one if necessary. + + if (wordprocessingDocument.MainDocumentPart is null) + { + wordprocessingDocument.AddMainDocumentPart(); + } + + if (wordprocessingDocument.MainDocumentPart!.Document is null) + { + wordprocessingDocument.MainDocumentPart.Document = new Document(); + } + + if (wordprocessingDocument.MainDocumentPart.Document.Body is null) + { + wordprocessingDocument.MainDocumentPart.Document.Body = new Body(); + } + + Body body = wordprocessingDocument.MainDocumentPart.Document.Body; + + // Create a table. + Table tbl = new Table(); + + // Set the style and width for the table. + TableProperties tableProp = new TableProperties(); + TableStyle tableStyle = new TableStyle() { Val = "TableGrid" }; + + // Make the table width 100% of the page width. + TableWidth tableWidth = new TableWidth() { Width = "5000", Type = TableWidthUnitValues.Pct }; + + // Apply + tableProp.Append(tableStyle, tableWidth); + tbl.AppendChild(tableProp); + + // Add 3 columns to the table. + TableGrid tg = new TableGrid(new GridColumn(), new GridColumn(), new GridColumn()); + tbl.AppendChild(tg); + + // Create 1 row to the table. + TableRow tr1 = new TableRow(); + + // Add a cell to each column in the row. + TableCell tc1 = new TableCell(new Paragraph(new Run(new Text("1")))); + TableCell tc2 = new TableCell(new Paragraph(new Run(new Text("2")))); + TableCell tc3 = new TableCell(new Paragraph(new Run(new Text("3")))); + tr1.Append(tc1, tc2, tc3); + + // Add row to the table. + tbl.AppendChild(tr1); + + // Add the table to the document + body.AppendChild(tbl); + + return tbl.LocalName; + } +} +// + +Console.WriteLine($"Inserted {InsertTableInDoc(args[0])}"); \ No newline at end of file diff --git a/samples/word/insert_table_in_doc/cs/insert_table_in_doc_cs.csproj b/samples/word/insert_table_in_doc/cs/insert_table_in_doc_cs.csproj new file mode 100644 index 00000000..6b512ec9 --- /dev/null +++ b/samples/word/insert_table_in_doc/cs/insert_table_in_doc_cs.csproj @@ -0,0 +1 @@ + diff --git a/samples/word/insert_table_in_doc/vb/Program.vb b/samples/word/insert_table_in_doc/vb/Program.vb new file mode 100644 index 00000000..3ca22a93 --- /dev/null +++ b/samples/word/insert_table_in_doc/vb/Program.vb @@ -0,0 +1,59 @@ +Imports DocumentFormat.OpenXml +Imports DocumentFormat.OpenXml.Packaging +Imports DocumentFormat.OpenXml.Wordprocessing +Imports BottomBorder = DocumentFormat.OpenXml.Wordprocessing.BottomBorder +Imports LeftBorder = DocumentFormat.OpenXml.Wordprocessing.LeftBorder +Imports RightBorder = DocumentFormat.OpenXml.Wordprocessing.RightBorder +Imports Run = DocumentFormat.OpenXml.Wordprocessing.Run +Imports Table = DocumentFormat.OpenXml.Wordprocessing.Table +Imports Text = DocumentFormat.OpenXml.Wordprocessing.Text +Imports TopBorder = DocumentFormat.OpenXml.Wordprocessing.TopBorder + +Module MyModule + + Sub Main(args As String()) + InsertTableInDoc(args(0)) + End Sub + ' + Public Sub InsertTableInDoc(ByVal filepath As String) + ' Open a WordprocessingDocument for editing using the filepath. + Using wordprocessingDocument As WordprocessingDocument = WordprocessingDocument.Open(filepath, True) + ' Assign a reference to the existing document body. + Dim body As Body = wordprocessingDocument.MainDocumentPart.Document.Body + + ' Create a table. + Dim tbl As New Table() + + ' Set the style and width for the table. + Dim tableProp As New TableProperties() + Dim tableStyle As New TableStyle() With {.Val = "TableGrid"} + + ' Make the table width 100% of the page width. + Dim tableWidth As New TableWidth() With {.Width = "5000", .Type = TableWidthUnitValues.Pct} + + ' Apply + tableProp.Append(tableStyle, tableWidth) + tbl.AppendChild(tableProp) + + ' Add 3 columns to the table. + Dim tg As New TableGrid(New GridColumn(), New GridColumn(), New GridColumn()) + tbl.AppendChild(tg) + + ' Create 1 row to the table. + Dim tr1 As New TableRow() + + ' Add a cell to each column in the row. + Dim tc1 As New TableCell(New Paragraph(New Run(New Text("1")))) + Dim tc2 As New TableCell(New Paragraph(New Run(New Text("2")))) + Dim tc3 As New TableCell(New Paragraph(New Run(New Text("3")))) + tr1.Append(tc1, tc2, tc3) + + ' Add row to the table. + tbl.AppendChild(tr1) + + ' Add the table to the document + body.AppendChild(tbl) + End Using + End Sub + ' +End Module \ No newline at end of file diff --git a/samples/word/insert_table_in_doc/vb/insert_table_in_doc_vb.vbproj b/samples/word/insert_table_in_doc/vb/insert_table_in_doc_vb.vbproj new file mode 100644 index 00000000..6b512ec9 --- /dev/null +++ b/samples/word/insert_table_in_doc/vb/insert_table_in_doc_vb.vbproj @@ -0,0 +1 @@ + diff --git a/samples/word/replace_the_styles_parts/vb/Program.vb b/samples/word/replace_the_styles_parts/vb/Program.vb index 586a8df3..602f3802 100644 --- a/samples/word/replace_the_styles_parts/vb/Program.vb +++ b/samples/word/replace_the_styles_parts/vb/Program.vb @@ -18,7 +18,7 @@ Module Program End If ' Extract and copy the stylesWithEffects part. To fully support - ' round-tripping from Word 2013 to Word 2010, you should + ' round-tripping from Word 2013+ to Word 2010, you should ' replace this part, as well. node = ExtractStylesPart(fromDoc, True) If node IsNot Nothing Then diff --git a/samples/word/set_the_font_for_a_text_run/cs/Program.cs b/samples/word/set_the_font_for_a_text_run/cs/Program.cs index c885f445..bc2ad15a 100644 --- a/samples/word/set_the_font_for_a_text_run/cs/Program.cs +++ b/samples/word/set_the_font_for_a_text_run/cs/Program.cs @@ -1,9 +1,9 @@ +// using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System; using System.Linq; -SetRunFont(args[0]); // Set the font for a text run. static void SetRunFont(string fileName) @@ -11,6 +11,7 @@ static void SetRunFont(string fileName) // Open a Wordprocessing document for editing. using (WordprocessingDocument package = WordprocessingDocument.Open(fileName, true)) { + // // Set the font to Arial to the first Run. // Use an object initializer for RunProperties and rPr. RunProperties rPr = new RunProperties( @@ -18,7 +19,9 @@ static void SetRunFont(string fileName) { Ascii = "Arial" }); + // + // if (package.MainDocumentPart is null) { throw new ArgumentNullException("MainDocumentPart is null."); @@ -29,5 +32,9 @@ static void SetRunFont(string fileName) // Save changes to the MainDocumentPart part. package.MainDocumentPart.Document.Save(); + // } -} \ No newline at end of file +} +// + +SetRunFont(args[0]); diff --git a/samples/word/set_the_font_for_a_text_run/vb/Program.vb b/samples/word/set_the_font_for_a_text_run/vb/Program.vb index cfcdf4e5..d7621f58 100644 --- a/samples/word/set_the_font_for_a_text_run/vb/Program.vb +++ b/samples/word/set_the_font_for_a_text_run/vb/Program.vb @@ -1,8 +1,10 @@ +' Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Wordprocessing Module Program Sub Main(args As String()) + SetRunFont(args(0)) End Sub @@ -12,14 +14,21 @@ Module Program ' Open a Wordprocessing document for editing. Dim package As WordprocessingDocument = WordprocessingDocument.Open(fileName, True) Using (package) + + ' ' Set the font to Arial to the first Run. + ' Use an object initializer for RunProperties and rPr. Dim rPr As RunProperties = New RunProperties(New RunFonts With {.Ascii = "Arial"}) - Dim r As Run = package.MainDocumentPart.Document.Descendants(Of Run).First + ' + ' + Dim r As Run = package.MainDocumentPart.Document.Descendants(Of Run).First r.PrependChild(Of RunProperties)(rPr) + ' ' Save changes to the main document part. package.MainDocumentPart.Document.Save() End Using End Sub -End Module \ No newline at end of file +End Module +' diff --git a/samples/word/structure_of_a_wordprocessingml/cs/Program.cs b/samples/word/structure_of_a_wordprocessingml/cs/Program.cs index 53725908..f60bb1ea 100644 --- a/samples/word/structure_of_a_wordprocessingml/cs/Program.cs +++ b/samples/word/structure_of_a_wordprocessingml/cs/Program.cs @@ -1,8 +1,7 @@ +// using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; -CreateWordDoc(args[0], args[1]); - static void CreateWordDoc(string filepath, string msg) { using (WordprocessingDocument doc = WordprocessingDocument.Create(filepath, DocumentFormat.OpenXml.WordprocessingDocumentType.Document)) @@ -16,7 +15,10 @@ static void CreateWordDoc(string filepath, string msg) Paragraph para = body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); - // String msg contains the text, "Hello, Word!" + // String msg contains the text from the msg parameter" run.AppendChild(new Text(msg)); } } +// + +CreateWordDoc(args[0], args[1]); diff --git a/samples/word/structure_of_a_wordprocessingml/vb/Program.vb b/samples/word/structure_of_a_wordprocessingml/vb/Program.vb index 0a37c0b8..9ab865ea 100644 --- a/samples/word/structure_of_a_wordprocessingml/vb/Program.vb +++ b/samples/word/structure_of_a_wordprocessingml/vb/Program.vb @@ -1,9 +1,11 @@ +' Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Wordprocessing Module MyModule Sub Main(args As String()) + CreateWordDoc(args(0), args(1)) End Sub Sub CreateWordDoc(filepath As String, msg As String) @@ -17,8 +19,9 @@ Module MyModule Dim para As Paragraph = body.AppendChild(New Paragraph()) Dim run As Run = para.AppendChild(New Run()) - ' String msg contains the text, "Hello, Word!" + ' String msg contains the text from the msg parameter run.AppendChild(New Text(msg)) End Using End Sub -End Module \ No newline at end of file +End Module +' diff --git a/samples/word/validate/cs/Program.cs b/samples/word/validate/cs/Program.cs index b511d765..44bc1ba3 100644 --- a/samples/word/validate/cs/Program.cs +++ b/samples/word/validate/cs/Program.cs @@ -1,9 +1,9 @@ +// using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Validation; using DocumentFormat.OpenXml.Wordprocessing; using System; -ValidateCorruptedWordDocument(args[0]); static void ValidateWordDocument(string filepath) { @@ -92,4 +92,7 @@ static void ValidateCorruptedWordDocument(string filepath) Console.WriteLine(ex.Message); } } -} \ No newline at end of file +} +// + +ValidateCorruptedWordDocument(args[0]); \ No newline at end of file diff --git a/samples/word/validate/vb/Program.vb b/samples/word/validate/vb/Program.vb index 2147514f..1bf1365c 100644 --- a/samples/word/validate/vb/Program.vb +++ b/samples/word/validate/vb/Program.vb @@ -1,13 +1,14 @@ +' Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Validation Imports DocumentFormat.OpenXml.Wordprocessing Module Program Sub Main(args As String()) + ValidateWordDocument(args(0)) + ValidateCorruptedWordDocument(args(0)) End Sub - - Public Sub ValidateWordDocument(ByVal filepath As String) Using wordprocessingDocument__1 As WordprocessingDocument = WordprocessingDocument.Open(filepath, True) Try @@ -63,4 +64,5 @@ Module Program End Try End Using End Sub -End Module \ No newline at end of file +End Module +' \ No newline at end of file diff --git a/samples/word/working_with_paragraphs/cs/Program.cs b/samples/word/working_with_paragraphs/cs/Program.cs index 63070bbb..49ee3ad9 100644 --- a/samples/word/working_with_paragraphs/cs/Program.cs +++ b/samples/word/working_with_paragraphs/cs/Program.cs @@ -1,8 +1,8 @@ +// using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System; -WriteToWordDoc(args[0], args[1]); static void WriteToWordDoc(string filepath, string txt) { @@ -24,3 +24,6 @@ static void WriteToWordDoc(string filepath, string txt) run.AppendChild(new Text(txt)); } } +// + +WriteToWordDoc(args[0], args[1]); \ No newline at end of file diff --git a/samples/word/working_with_paragraphs/vb/Program.vb b/samples/word/working_with_paragraphs/vb/Program.vb index ecd62fab..846b58ca 100644 --- a/samples/word/working_with_paragraphs/vb/Program.vb +++ b/samples/word/working_with_paragraphs/vb/Program.vb @@ -1,9 +1,11 @@ +' Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Wordprocessing Module MyModule Sub Main(args As String()) + WriteToWordDoc(args(0), args(1)) End Sub Public Sub WriteToWordDoc(ByVal filepath As String, ByVal txt As String) @@ -20,4 +22,5 @@ Module MyModule End Using End Sub -End Module \ No newline at end of file +End Module +' \ No newline at end of file diff --git a/samples/word/working_with_runs/cs/Program.cs b/samples/word/working_with_runs/cs/Program.cs index 3523e2a1..6c46680a 100644 --- a/samples/word/working_with_runs/cs/Program.cs +++ b/samples/word/working_with_runs/cs/Program.cs @@ -1,8 +1,7 @@ +// using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; -WriteToWordDoc(args[0], args[1]); - static void WriteToWordDoc(string filepath, string txt) { // Open a WordprocessingDocument for editing using the filepath. @@ -22,3 +21,5 @@ static void WriteToWordDoc(string filepath, string txt) run.AppendChild(new Text(txt)); } } +// +WriteToWordDoc(args[0], args[1]); \ No newline at end of file diff --git a/samples/word/working_with_runs/vb/Program.vb b/samples/word/working_with_runs/vb/Program.vb index 469a9cd9..274ada15 100644 --- a/samples/word/working_with_runs/vb/Program.vb +++ b/samples/word/working_with_runs/vb/Program.vb @@ -1,9 +1,11 @@ +' Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Wordprocessing Module MyModule Sub Main(args As String()) + WriteToWordDoc(args(0), args(1)) End Sub Public Sub WriteToWordDoc(ByVal filepath As String, ByVal txt As String) @@ -22,4 +24,5 @@ Module MyModule run.AppendChild(New Text(txt)) End Using End Sub -End Module \ No newline at end of file +End Module +' \ No newline at end of file diff --git a/samples/word/working_with_tables/cs/Program.cs b/samples/word/working_with_tables/cs/Program.cs new file mode 100644 index 00000000..cfa38a01 --- /dev/null +++ b/samples/word/working_with_tables/cs/Program.cs @@ -0,0 +1,68 @@ +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; +using System; + +// +static string InsertTableInDoc(string filepath) +{ + // Open a WordprocessingDocument for editing using the filepath. + using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filepath, true)) + { + // Assign a reference to the existing document body or add one if necessary. + + if (wordprocessingDocument.MainDocumentPart is null) + { + wordprocessingDocument.AddMainDocumentPart(); + } + + if (wordprocessingDocument.MainDocumentPart!.Document is null) + { + wordprocessingDocument.MainDocumentPart.Document = new Document(); + } + + if (wordprocessingDocument.MainDocumentPart.Document.Body is null) + { + wordprocessingDocument.MainDocumentPart.Document.Body = new Body(); + } + + Body body = wordprocessingDocument.MainDocumentPart.Document.Body; + + // Create a table. + Table tbl = new Table(); + + // Set the style and width for the table. + TableProperties tableProp = new TableProperties(); + TableStyle tableStyle = new TableStyle() { Val = "TableGrid" }; + + // Make the table width 100% of the page width. + TableWidth tableWidth = new TableWidth() { Width = "5000", Type = TableWidthUnitValues.Pct }; + + // Apply + tableProp.Append(tableStyle, tableWidth); + tbl.AppendChild(tableProp); + + // Add 3 columns to the table. + TableGrid tg = new TableGrid(new GridColumn(), new GridColumn(), new GridColumn()); + tbl.AppendChild(tg); + + // Create 1 row to the table. + TableRow tr1 = new TableRow(); + + // Add a cell to each column in the row. + TableCell tc1 = new TableCell(new Paragraph(new Run(new Text("1")))); + TableCell tc2 = new TableCell(new Paragraph(new Run(new Text("2")))); + TableCell tc3 = new TableCell(new Paragraph(new Run(new Text("3")))); + tr1.Append(tc1, tc2, tc3); + + // Add row to the table. + tbl.AppendChild(tr1); + + // Add the table to the document + body.AppendChild(tbl); + + return tbl.LocalName; + } +} +// + +Console.WriteLine($"Inserted {InsertTableInDoc(args[0])}"); \ No newline at end of file diff --git a/samples/word/working_with_tables/cs/working_with_tables_cs.csproj b/samples/word/working_with_tables/cs/working_with_tables_cs.csproj new file mode 100644 index 00000000..6b512ec9 --- /dev/null +++ b/samples/word/working_with_tables/cs/working_with_tables_cs.csproj @@ -0,0 +1 @@ + diff --git a/samples/word/working_with_tables/vb/Program.vb b/samples/word/working_with_tables/vb/Program.vb new file mode 100644 index 00000000..3ca22a93 --- /dev/null +++ b/samples/word/working_with_tables/vb/Program.vb @@ -0,0 +1,59 @@ +Imports DocumentFormat.OpenXml +Imports DocumentFormat.OpenXml.Packaging +Imports DocumentFormat.OpenXml.Wordprocessing +Imports BottomBorder = DocumentFormat.OpenXml.Wordprocessing.BottomBorder +Imports LeftBorder = DocumentFormat.OpenXml.Wordprocessing.LeftBorder +Imports RightBorder = DocumentFormat.OpenXml.Wordprocessing.RightBorder +Imports Run = DocumentFormat.OpenXml.Wordprocessing.Run +Imports Table = DocumentFormat.OpenXml.Wordprocessing.Table +Imports Text = DocumentFormat.OpenXml.Wordprocessing.Text +Imports TopBorder = DocumentFormat.OpenXml.Wordprocessing.TopBorder + +Module MyModule + + Sub Main(args As String()) + InsertTableInDoc(args(0)) + End Sub + ' + Public Sub InsertTableInDoc(ByVal filepath As String) + ' Open a WordprocessingDocument for editing using the filepath. + Using wordprocessingDocument As WordprocessingDocument = WordprocessingDocument.Open(filepath, True) + ' Assign a reference to the existing document body. + Dim body As Body = wordprocessingDocument.MainDocumentPart.Document.Body + + ' Create a table. + Dim tbl As New Table() + + ' Set the style and width for the table. + Dim tableProp As New TableProperties() + Dim tableStyle As New TableStyle() With {.Val = "TableGrid"} + + ' Make the table width 100% of the page width. + Dim tableWidth As New TableWidth() With {.Width = "5000", .Type = TableWidthUnitValues.Pct} + + ' Apply + tableProp.Append(tableStyle, tableWidth) + tbl.AppendChild(tableProp) + + ' Add 3 columns to the table. + Dim tg As New TableGrid(New GridColumn(), New GridColumn(), New GridColumn()) + tbl.AppendChild(tg) + + ' Create 1 row to the table. + Dim tr1 As New TableRow() + + ' Add a cell to each column in the row. + Dim tc1 As New TableCell(New Paragraph(New Run(New Text("1")))) + Dim tc2 As New TableCell(New Paragraph(New Run(New Text("2")))) + Dim tc3 As New TableCell(New Paragraph(New Run(New Text("3")))) + tr1.Append(tc1, tc2, tc3) + + ' Add row to the table. + tbl.AppendChild(tr1) + + ' Add the table to the document + body.AppendChild(tbl) + End Using + End Sub + ' +End Module \ No newline at end of file diff --git a/samples/word/working_with_tables/vb/working_with_tables_vb.vbproj b/samples/word/working_with_tables/vb/working_with_tables_vb.vbproj new file mode 100644 index 00000000..6b512ec9 --- /dev/null +++ b/samples/word/working_with_tables/vb/working_with_tables_vb.vbproj @@ -0,0 +1 @@ + From da68a6921a306c656de5195f42c5921e3a24a36b Mon Sep 17 00:00:00 2001 From: Taylor Southwick Date: Thu, 25 Jan 2024 15:48:25 -0800 Subject: [PATCH 002/103] Use xref (#308) --- .openpublishing.publish.config.json | 31 ++++++++++++++++- docs/general/features.md | 33 +++++------------- ...to-add-a-new-document-part-to-a-package.md | 6 ++-- ...ackage-part-to-a-document-part-in-a-dif.md | 34 +++++++------------ docs/general/how-to-create-a-package.md | 29 +++++----------- ...tents-of-a-document-part-from-a-package.md | 4 +-- ...o-remove-a-document-part-from-a-package.md | 4 +-- ...heme-part-in-a-word-processing-document.md | 10 +++--- ...rch-and-replace-text-in-a-document-part.md | 4 +-- docs/general/overview.md | 1 - ...paragraph-in-a-word-processing-document.md | 2 +- ...n-a-table-in-a-word-processing-document.md | 4 +-- ...ssing-document-by-providing-a-file-name.md | 10 +++--- ...comment-into-a-word-processing-document.md | 2 +- ...picture-into-a-word-processing-document.md | 4 +-- ...a-table-into-a-word-processing-document.md | 4 +-- ...rocessing-document-for-read-only-access.md | 20 +++++------ ...-word-processing-document-from-a-stream.md | 6 ++-- ...-add-text-to-a-word-processing-document.md | 4 +-- ...en-text-from-a-word-processing-document.md | 4 +-- ...-values-from-a-word-processing-document.md | 4 +-- ...omments-from-a-word-processing-document.md | 2 +- ...-property-in-a-word-processing-document.md | 2 +- .../how-to-set-the-font-for-a-text-run.md | 2 +- docs/word/overview.md | 2 +- 25 files changed, 110 insertions(+), 118 deletions(-) diff --git a/.openpublishing.publish.config.json b/.openpublishing.publish.config.json index 5e32ffad..e83d1548 100644 --- a/.openpublishing.publish.config.json +++ b/.openpublishing.publish.config.json @@ -6,13 +6,42 @@ "build_output_subfolder": "open-xml-docs", "locale": "en-us", "monikers": [], - "moniker_ranges": [], + "moniker_ranges": [ + "openxml-2.7.1", + "openxml-2.7.2", + "openxml-2.8.0", + "openxml-2.8.1", + "openxml-2.9.0", + "openxml-2.9.1", + "openxml-2.10.0", + "openxml-2.10.1", + "openxml-2.11.0", + "openxml-2.11.1", + "openxml-2.11.2", + "openxml-2.11.3", + "openxml-2.12.0", + "openxml-2.12.1", + "openxml-2.12.2", + "openxml-2.12.3", + "openxml-2.13.0", + "openxml-2.13.1", + "openxml-2.14.0", + "openxml-2.15.0", + "openxml-2.16.0", + "openxml-2.17.1", + "openxml-2.18.0", + "openxml-2.19.0", + "openxml-2.20.0", + "openxml-3.0.0", + "openxml-3.0.1" + ], "open_to_public_contributors": true, "customized_tasks": { "docset_prebuild": [ "_dependentPackages/CommonPlugins/tools/JoinTOC.ps1" ] }, + "xref_query_tags": [ "/dotnet" ], "type_mapping": { "Conceptual": "Content", "ManagedReference": "Content", diff --git a/docs/general/features.md b/docs/general/features.md index 665a762d..6c3587cd 100644 --- a/docs/general/features.md +++ b/docs/general/features.md @@ -38,12 +38,13 @@ private sealed class PrivateFeature { } ``` + > [!NOTE] > The feature collection on elements is readonly. This is due to memory issues if it is made writeable. If this is needed, please engage on https://github.com/dotnet/open-xml-sdk to let us know your scenario. ## Visualizing Registered Features -The in-box implementations of the `IFeatureCollection` provide a helpful debug view so you can see what features are available and what their properties/fields are: +The in-box implementations of the provide a helpful debug view so you can see what features are available and what their properties/fields are: ![Features Debug View](../media/feature-debug-view.png) @@ -51,7 +52,7 @@ The in-box implementations of the `IFeatureCollection` provide a helpful debug v The features that are currently available are described below and at what scope they are available: -### IDisposableFeature +### This feature allows for registering actions that need to run when a package or a part is destroyed or disposed: @@ -65,7 +66,7 @@ part.Features.Get().Register(() => /* Some action that is ca Packages and parts will have their own implementations of this feature. Elements will retrieve the feature for their containing part if available. -### IPackageEventsFeature +### This feature allows getting event notifications of when a package is changed: @@ -79,7 +80,7 @@ var feature = package.Features.GetRequired(); > [!NOTE] > There may be times when the package is changed but an event is not fired. Not all areas have been identified where it would make sense to raise an event. Please file an issue if you find one. -### IPartEventsFeature +### This feature allows getting event notifications of when an event is being created. This is a feature that is added to the part or package: @@ -95,7 +96,7 @@ Generally, assume that there may be a singleton implementation for the events an > [!NOTE] > There may be times when the part is changed but an event is not fired. Not all areas have been identified where it would make sense to raise an event. Please file an issue if you find one. -### IPartRootEventsFeature +### This feature allows getting event notifications of when a part root is being modified/loaded/created/etc. This is a feature that is added to the part level feature: @@ -111,11 +112,11 @@ Generally, assume that there may be a singleton implementation for the events an > [!NOTE] > There may be times when the part root is changed but an event is not fired. Not all areas have been identified where it would make sense to raise an event. Please file an issue if you find one. -### IRandomNumberGeneratorFeature +### This feature allows for a shared service to generate random numbers and fill an array. -### IParagraphIdGeneratorFeature +### This feature allows for population and tracking of elements that contain paragraph ids. By default, this will ensure uniqueness of values and ensure that values that do exist are valid per the constraints of the standard. To use this feature: @@ -159,21 +160,3 @@ body2.AddChild(p2); Assert.NotEqual(p1.ParagraphId, p2.ParagraphId); Assert.Equal(2, shared.Count); ``` - -### IPartRootXElementFeature - -This feature allows operating on an `OpenXmlPart` by using XLinq features and directly manipulating `XElement` nodes. - -```csharp -OpenXmlPart part = GetSomePart(); - -var node = new(W.document, new XAttribute(XNamespace.Xmlns + "w", W.w), - new XElement(W.body, - new XElement(W.p, - new XElement(W.r, - new XElement(W.t, "Hello World!"))))); - -part.SetXElement(node); -``` - -This `XElement` is cached but will be kept in sync with the underlying part if it were to change. 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 46e18fc8..bc5ba2d2 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 @@ -21,7 +21,7 @@ This topic shows how to use the classes in the Open XML SDK for Office to add a ## Get 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 of the **[DocumentFormat.OpenXml.Packaging.WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument)** 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. +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 @@ -40,14 +40,14 @@ The code starts with opening a package file by passing a file name to one of the *** -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 **WordprocessingDocument** class in the Open XML SDK +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[Structure](../includes/word/structure.md)] ## How the sample code works -After opening the document for editing, in the **using** statement, as a **WordprocessingDocument** 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 +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] 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 272ba2ab..5d9bf19f 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 @@ -30,7 +30,7 @@ programmatically. -------------------------------------------------------------------------------- ## Getting a WordprocessingDocument Object -To open an existing document, instantiate the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) class as shown in +To open an existing document, instantiate the class as shown in 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. @@ -57,19 +57,16 @@ order to enable editing the document. ``` *** - -The **using** statement provides a recommended +The `using` statement provides a recommended alternative to the typical .Create, .Save, .Close sequence. It ensures -that the **Dispose** method (internal method +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 **WordprocessingDocument** 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**. - +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 . -------------------------------------------------------------------------------- @@ -117,9 +114,9 @@ is stored in the ZIP item theme/theme1.xml: ## How the Sample Code Works To copy the contents of a document part in an Open XML package to a document part in a different package, the full path of the each word -processing document is passed in as a parameter to the **CopyThemeContent** method. The code then opens both -documents as **WordprocessingDocument** -objects, and creates variables that reference the **ThemePart** parts in each of the packages. +processing document is passed in as a parameter to the `CopyThemeContent` method. The code then opens both +documents as +objects, and creates variables that reference the parts in each of the packages. ### [C#](#tab/cs-1) ```csharp @@ -144,8 +141,8 @@ objects, and creates variables that reference the **ThemePart** parts in each of *** -The code then reads the contents of the source **ThemePart** part by using a **StreamReader** object and writes to the target -**ThemePart** part by using a **StreamWriter** object. +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 @@ -170,7 +167,7 @@ The code then reads the contents of the source **ThemePart** part by using a **S -------------------------------------------------------------------------------- ## 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 +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." @@ -207,9 +204,4 @@ Following is the complete sample code in both C\# and Visual Basic. -------------------------------------------------------------------------------- ## See also - - [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) - - - - diff --git a/docs/general/how-to-create-a-package.md b/docs/general/how-to-create-a-package.md index 0aa2c48b..c40dea47 100644 --- a/docs/general/how-to-create-a-package.md +++ b/docs/general/how-to-create-a-package.md @@ -23,29 +23,25 @@ from content in the form of **WordprocessingML** XML markup. [!include[Structure](../includes/word/packages-and-document-parts.md)] - ## Getting a WordprocessingDocument Object -In the Open XML SDK, the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) class represents a Word document package. To create a Word document, you create an instance -of the **WordprocessingDocument** class and +In the Open XML SDK, the class represents a Word document package. To create a Word document, you create an instance +of 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. -To create the class instance you call the [Create(String, WordprocessingDocumentType)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.create) -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 takes a full path +To create the class instance you call . Several methods are +provided, each with a different signature. The first parameter takes a full path string that represents the document that you want to create. The second -parameter is a member of the [WordprocessingDocumentType](/dotnet/api/documentformat.openxml.wordprocessingdocumenttype) enumeration. +parameter is a member of the enumeration. This parameter represents the type of document. For example, there is a -different member of the [WordProcessingDocumentType](/dotnet/api/documentformat.openxml.wordprocessingdocumenttype) enumeration for each +different member of the enumeration for each of document, template, and the macro enabled variety of document and template. > [!NOTE] -> Carefully select the appropriate **WordProcessingDocumentType** and verify that the persisted file has the correct, matching file extension. If the **WordProcessingDocumentType** does not match the file extension, an error occurs when you open the file in Microsoft Word. The code that calls the **Create** method is part of a **using** statement followed by a bracketed block, as shown in the following code example. +> 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 @@ -63,19 +59,18 @@ template. ``` *** - 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 **WordprocessingDocument** class in the Open XML SDK +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**. Once you have created the Word document package, you can add parts to -it. To add the main document part you call the [AddMainDocumentPart()](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.addmaindocumentpart) method of the **WordprocessingDocument** class. Having done that, +it. To add the main document part you call . Having done that, you can set about adding the document structure and text. [!include[Structure](../includes/word/structure.md)] @@ -99,7 +94,6 @@ call: ``` *** - After you run the program, open the created file "myPkg4.docx" and examine its content; it should be one paragraph that contains the phrase "Hello world!" @@ -114,9 +108,4 @@ Following is the complete sample code in both C\# and Visual Basic. ## See also - - - [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) - - - 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 8f3cb980..8f2a83bc 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 @@ -30,7 +30,7 @@ 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 -method or C\# static method) of the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) class that takes a +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 @@ -60,7 +60,7 @@ 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 **WordprocessingDocument** class in the Open XML SDK +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 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 52876957..fcfacedf 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 @@ -59,7 +59,7 @@ 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 **WordprocessingDocument** class in the Open XML SDK +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 @@ -99,7 +99,7 @@ introduces the settings element in a **PresentationML** package. -------------------------------------------------------------------------------- ## How the Sample Code Works -After you have opened the document, in the **using** statement, as a **WordprocessingDocument** object, you create a +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** 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 7b3406c3..a8648b65 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 @@ -26,7 +26,7 @@ document. ## Getting a WordprocessingDocument Object In the sample code, you start by opening the word processing file by -instantiating the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) class as shown in +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 @@ -56,7 +56,7 @@ 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 **WordprocessingDocument** class in the +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 @@ -163,10 +163,10 @@ delete the old theme part. ``` *** -You can then create add a new **ThemePart** +You can then create add a new object and add it to the **MainDocumentPart** -object. Then you add content by using a **StreamReader** and **StreamWriter** objects to copy the theme from the -*themeFile* to the **ThemePart** object. +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 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 eb2616ab..9a73ba0a 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 @@ -29,7 +29,7 @@ processing document. --------------------------------------------------------------------------------- ## Getting a WordprocessingDocument Object In the sample code, you start by opening the word processing file by -instantiating the **[WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument)** class as shown in +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 @@ -59,7 +59,7 @@ 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 **WordprocessingDocument** class in the +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 diff --git a/docs/general/overview.md b/docs/general/overview.md index 0aae015e..04771389 100644 --- a/docs/general/overview.md +++ b/docs/general/overview.md @@ -19,7 +19,6 @@ ms.localizationpriority: high This section provides how-to topics for working with documents and packages using the Open XML SDK. - ## In this section - [Features in Open XML SDK](features.md) 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 a04e7ab0..94fe5f23 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 @@ -41,7 +41,7 @@ The following sections in this topic explain the implementation of this method a ## Get a WordprocessingDocument object -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 [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) class represents a Word document package. To open and work with a Word document, create an instance of the **WordprocessingDocument** 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. +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. diff --git a/docs/word/how-to-change-text-in-a-table-in-a-word-processing-document.md b/docs/word/how-to-change-text-in-a-table-in-a-word-processing-document.md index 1e92cd22..d6232a15 100644 --- a/docs/word/how-to-change-text-in-a-table-in-a-word-processing-document.md +++ b/docs/word/how-to-change-text-in-a-table-in-a-word-processing-document.md @@ -23,7 +23,7 @@ This topic shows how to use the Open XML SDK for Office to programmatically chan ## Open the Existing Document -To open an existing document, instantiate the **WordprocessingDocument** class as shown in the following **using** statement. In the same statement, open the word processing file at the specified **filepath** by using the **Open** method, with the Boolean parameter set to **true** to enable editing the document. +To open an existing document, instantiate the class as shown in the following **using** statement. In the same statement, open the word processing file at the specified **filepath** by using the **Open** method, with the Boolean parameter set to **true** to enable editing the document. ### [C#](#tab/cs-0) ```csharp @@ -48,7 +48,7 @@ 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**. Because the **WordprocessingDocument** class in the Open XML SDK +object that is created or named in the **using** statement, in this case **doc**. 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 diff --git a/docs/word/how-to-create-a-word-processing-document-by-providing-a-file-name.md b/docs/word/how-to-create-a-word-processing-document-by-providing-a-file-name.md index ed8c7ce9..05e0f3ea 100644 --- a/docs/word/how-to-create-a-word-processing-document-by-providing-a-file-name.md +++ b/docs/word/how-to-create-a-word-processing-document-by-providing-a-file-name.md @@ -23,9 +23,9 @@ Office to programmatically create a word processing document. -------------------------------------------------------------------------------- ## Creating a WordprocessingDocument Object -In the Open XML SDK, the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) class represents a +In the Open XML SDK, the class represents a Word document package. To create a Word document, you create an instance -of the **WordprocessingDocument** class and +of 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 @@ -36,7 +36,7 @@ method. Several [Create()](/dotnet/api/documentformat.openxml.packaging.wordproc different signature. The sample code in this topic uses the **Create** method with a signature that requires two parameters. The first parameter takes a full path string that represents the document that you want to create. The second parameter is a member -of the [WordprocessingDocumentType](/dotnet/api/documentformat.openxml.wordprocessingdocumenttype) enumeration. +of the enumeration. This parameter represents the type of document. For example, there is a different member of the **WordProcessingDocumentType** enumeration for each of document, template, and the macro enabled variety of document and @@ -74,14 +74,14 @@ 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 **wordDocument**. Because the **WordprocessingDocument** class in the Open XML SDK +object that is created or named in the **using** statement, in this case **wordDocument**. 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**. Once you have created the Word document package, you can add parts to -it. To add the main document part you call the [AddMainDocumentPart()](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.addmaindocumentpart) method of the **WordprocessingDocument** class. Having done that, +it. To add the main document part you call the method of the class. Having done that, you can set about adding the document structure and text. diff --git a/docs/word/how-to-insert-a-comment-into-a-word-processing-document.md b/docs/word/how-to-insert-a-comment-into-a-word-processing-document.md index db3ebbe7..02f2c21f 100644 --- a/docs/word/how-to-insert-a-comment-into-a-word-processing-document.md +++ b/docs/word/how-to-insert-a-comment-into-a-word-processing-document.md @@ -24,7 +24,7 @@ word processing document. -------------------------------------------------------------------------------- ## Open the Existing Document for Editing -To open an existing document, instantiate the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) class as shown in +To open an existing document, instantiate the class as shown in the following **using** statement. In the same statement, open the word processing file at the specified *filepath* by using the [Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) method, with the diff --git a/docs/word/how-to-insert-a-picture-into-a-word-processing-document.md b/docs/word/how-to-insert-a-picture-into-a-word-processing-document.md index d657ae0e..4a17b366 100644 --- a/docs/word/how-to-insert-a-picture-into-a-word-processing-document.md +++ b/docs/word/how-to-insert-a-picture-into-a-word-processing-document.md @@ -25,7 +25,7 @@ This topic shows how to use the classes in the Open XML SDK for Office to progra ## Opening an Existing Document for Editing -To open an existing document, instantiate the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) class as shown in +To open an existing document, instantiate the class as shown in the following **using** statement. In the same statement, open the word processing file at the specified **filepath** by using the [Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) method, with the Boolean parameter set to **true** in order to @@ -56,7 +56,7 @@ that is 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 -*wordprocessingDocument*. Because the **WordprocessingDocument** class in the Open XML SDK +*wordprocessingDocument*. 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 diff --git a/docs/word/how-to-insert-a-table-into-a-word-processing-document.md b/docs/word/how-to-insert-a-table-into-a-word-processing-document.md index cc99b319..e145ca17 100644 --- a/docs/word/how-to-insert-a-table-into-a-word-processing-document.md +++ b/docs/word/how-to-insert-a-table-into-a-word-processing-document.md @@ -24,7 +24,7 @@ document. ## Getting a WordprocessingDocument Object -To open an existing document, instantiate the **WordprocessingDocument** class as shown in the +To open an existing document, instantiate the class as shown in the following **using** statement. In the same statement, open the word processing file at the specified filepath by using the **Open** method, with the Boolean @@ -55,7 +55,7 @@ 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. Because the **WordprocessingDocument** class in the Open XML SDK +the using statement, in this case doc. 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 diff --git a/docs/word/how-to-open-a-word-processing-document-for-read-only-access.md b/docs/word/how-to-open-a-word-processing-document-for-read-only-access.md index f118cf78..79bdaf9f 100644 --- a/docs/word/how-to-open-a-word-processing-document-for-read-only-access.md +++ b/docs/word/how-to-open-a-word-processing-document-for-read-only-access.md @@ -33,13 +33,13 @@ programmatically open a read-only word processing document. -------------------------------------------------------------------------------- ## Create a WordprocessingDocument Object -In the Open XML SDK, the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) class represents a +In the Open XML SDK, the class represents a Word document package. To work with a Word document, first create an -instance of the **WordprocessingDocument** +instance of the class from the document, and then work with that instance. Once you create the instance from the document, you can then obtain access to the main document part that contains the text of the document. Every Open -XML package contains some number of parts. At a minimum, a **WordProcessingDocument** must contain a main +XML package contains some number of parts. At a minimum, a must contain a main document part that acts as a container for the main text of the document. The package can also contain additional parts. Notice that in a Word document, the text in the main document part is represented in @@ -51,10 +51,10 @@ editable are listed in the following table. Open Method|Class Library Reference Topic|Description --|--|-- -Open(String, Boolean)|[Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) |Create an instance of the **WordprocessingDocument** class from the specified file. -Open(Stream, Boolean)|[Open(Stream, Boolean)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) |Create an instance of the **WordprocessingDocument** class from the specified IO stream. -Open(String, Boolean, OpenSettings)|[Open(String, Boolean, OpenSettings)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) |Create an instance of the **WordprocessingDocument** class from the specified file. -Open(Stream, Boolean, OpenSettings)|[Open(Stream, Boolean, OpenSettings)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) |Create an instance of the **WordprocessingDocument** class from the specified I/O stream. +Open(String, Boolean)|[Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) |Create an instance of the class from the specified file. +Open(Stream, Boolean)|[Open(Stream, Boolean)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) |Create an instance of the class from the specified IO stream. +Open(String, Boolean, OpenSettings)|[Open(String, Boolean, OpenSettings)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) |Create an instance of the class from the specified file. +Open(Stream, Boolean, OpenSettings)|[Open(Stream, Boolean, OpenSettings)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) |Create an instance of the class from the specified I/O stream. The table above lists only those **Open** methods that accept a Boolean value as the second parameter to specify @@ -62,7 +62,7 @@ whether a document is editable. To open a document for read only access, you specify false for this parameter. Notice that two of the **Open** methods create -an instance of the **WordprocessingDocument** +an instance of the 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 the table above; with a signature that requires two parameters. The first parameter takes a string that @@ -90,7 +90,7 @@ Method. The other two **Open** methods create an -instance of the **WordprocessingDocument** +instance of the class based on an input/output stream. You might employ this approach, for instance, if you have a Microsoft SharePoint Foundation 2010 application that uses stream input/output, and you want to use the Open @@ -123,7 +123,7 @@ 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 read-only to begin with -prior to creating the instance of the **WordprocessingDocument** class, as shown in the +prior to creating the instance of the class, as shown in the second example in the sample code. The following code example performs this operation. diff --git a/docs/word/how-to-open-a-word-processing-document-from-a-stream.md b/docs/word/how-to-open-a-word-processing-document-from-a-stream.md index bbc88237..729c6443 100644 --- a/docs/word/how-to-open-a-word-processing-document-from-a-stream.md +++ b/docs/word/how-to-open-a-word-processing-document-from-a-stream.md @@ -37,13 +37,13 @@ adds text to the document behind the stream using the Open XML SDK. ## Creating a WordprocessingDocument Object -In the Open XML SDK, the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) class represents a +In the Open XML SDK, the class represents a Word document package. To work with a Word document, first create an -instance of the **WordprocessingDocument** +instance of the class from the document, and then work with that instance. When you create the instance from the document, you can then obtain access to the main document part that contains the text of the document. Every Open -XML package contains some number of parts. At a minimum, a **WordProcessingDocument** must contain a main +XML package contains some number of parts. At a minimum, a must contain a main document part that acts as a container for the main text of the document. The package can also contain additional parts. Notice that in a Word document, the text in the main document part is represented in diff --git a/docs/word/how-to-open-and-add-text-to-a-word-processing-document.md b/docs/word/how-to-open-and-add-text-to-a-word-processing-document.md index eb2dd7c6..b18ef6dd 100644 --- a/docs/word/how-to-open-and-add-text-to-a-word-processing-document.md +++ b/docs/word/how-to-open-and-add-text-to-a-word-processing-document.md @@ -34,9 +34,9 @@ elements, and their corresponding Open XML SDK classes. -------------------------------------------------------------------------------- ## Create a WordprocessingDocument Object -In the Open XML SDK, the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) class represents a +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 **WordprocessingDocument** +instance of the class from the document. When you create the instance from the document, you can then obtain access to the main document part that contains the text of the document. The text in the main document part is represented diff --git a/docs/word/how-to-remove-hidden-text-from-a-word-processing-document.md b/docs/word/how-to-remove-hidden-text-from-a-word-processing-document.md index 38b3c32e..718ab2ef 100644 --- a/docs/word/how-to-remove-hidden-text-from-a-word-processing-document.md +++ b/docs/word/how-to-remove-hidden-text-from-a-word-processing-document.md @@ -24,7 +24,7 @@ document. --------------------------------------------------------------------------------- ## Getting a WordprocessingDocument Object -To open an existing document, you instantiate the **WordprocessingDocument** class as shown in the +To open an existing document, you instantiate the class as shown in the following **using** statement. In the same statement, you open the word processing file with the specified *fileName* by using the **Open** method, with @@ -56,7 +56,7 @@ 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. Because the **WordprocessingDocument** class in the Open XML SDK +the using statement, in this case doc. 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 diff --git a/docs/word/how-to-retrieve-application-property-values-from-a-word-processing-document.md b/docs/word/how-to-retrieve-application-property-values-from-a-word-processing-document.md index c5448c1d..56340afa 100644 --- a/docs/word/how-to-retrieve-application-property-values-from-a-word-processing-document.md +++ b/docs/word/how-to-retrieve-application-property-values-from-a-word-processing-document.md @@ -24,7 +24,7 @@ This topic shows how to use the classes in the Open XML SDK for Office to progra ## Retrieving Application Properties -To retrieve application document properties, you can retrieve the **ExtendedFilePropertiesPart** property of a **WordprocessingDocument** object, and then retrieve the specific application property you need. To do this, you must first get a reference to the document, as shown in the following code. +To retrieve application document properties, you can retrieve the **ExtendedFilePropertiesPart** property of a object, and then retrieve the specific application property you need. To do this, you must first get a reference to the document, as shown in the following code. ### [C#](#tab/cs-0) ```csharp @@ -49,7 +49,7 @@ To retrieve application document properties, you can retrieve the **ExtendedFile *** -Given the reference to the **WordProcessingDocument** object, you can retrieve a reference to the **ExtendedFilePropertiesPart** property of the document. This object provides its own properties, each of which exposes one of the application document properties. +Given the reference to the object, you can retrieve a reference to the **ExtendedFilePropertiesPart** property of the document. This object provides its own properties, each of which exposes one of the application document properties. ### [C#](#tab/cs-1) ```csharp diff --git a/docs/word/how-to-retrieve-comments-from-a-word-processing-document.md b/docs/word/how-to-retrieve-comments-from-a-word-processing-document.md index 2d52a5b9..fc063dd6 100644 --- a/docs/word/how-to-retrieve-comments-from-a-word-processing-document.md +++ b/docs/word/how-to-retrieve-comments-from-a-word-processing-document.md @@ -24,7 +24,7 @@ part in a word processing document. -------------------------------------------------------------------------------- ## Open the Existing Document for Read-only Access -To open an existing document, instantiate the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) class as shown in +To open an existing document, instantiate the class as shown in the following **using** statement. In the same statement, open the word processing file at the specified **fileName** by using the [Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) method. To open the file for editing the Boolean parameter is set to **true**. In this example you just need to read the diff --git a/docs/word/how-to-set-a-custom-property-in-a-word-processing-document.md b/docs/word/how-to-set-a-custom-property-in-a-word-processing-document.md index 928192ae..cd601cbb 100644 --- a/docs/word/how-to-set-a-custom-property-in-a-word-processing-document.md +++ b/docs/word/how-to-set-a-custom-property-in-a-word-processing-document.md @@ -323,7 +323,7 @@ At this point, if the code has not thrown an exception, you can assume that the ## Working with the Document Given the **CustomDocumentProperty** object, the code next interacts with the document that you supplied in the parameters to the **SetCustomProperty** procedure. The code starts by opening the document in read/write mode by -using the [Open](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) method of the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) class. The code attempts to retrieve a reference to the custom file properties part by using the [CustomFilePropertiesPart](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.customfilepropertiespart) property of the document. +using the [Open](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) method of the class. The code attempts to retrieve a reference to the custom file properties part by using the [CustomFilePropertiesPart](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.customfilepropertiespart) property of the document. ### [C#](#tab/cs-5) ```csharp diff --git a/docs/word/how-to-set-the-font-for-a-text-run.md b/docs/word/how-to-set-the-font-for-a-text-run.md index ecdc934a..f4912f37 100644 --- a/docs/word/how-to-set-the-font-for-a-text-run.md +++ b/docs/word/how-to-set-the-font-for-a-text-run.md @@ -111,7 +111,7 @@ In this case, running the code sample produces an in-memory XML structure where the **RunProperties** element is added as the first child element of the **Run** element. It then saves the changes back to the [Save(MainDocumentPart)](/dotnet/api/documentformat.openxml.wordprocessing.document.save) object. Calling the -**Save** method of the [WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) object commits +**Save** method of the object commits changes made to the in-memory representation of the **MainDocumentPart** part back into the XML file for the **MainDocumentPart** (the document.xml file in the Wordprocessing package). diff --git a/docs/word/overview.md b/docs/word/overview.md index 2a23d16c..26cf33bb 100644 --- a/docs/word/overview.md +++ b/docs/word/overview.md @@ -65,7 +65,7 @@ This section provides how-to topics for working with word processing documents u - [Retrieve comments from a word processing document](how-to-retrieve-comments-from-a-word-processing-document.md) -- [Retrieve property values from a Word document by using the Open XML API](/office/open-xml/how-to-retrieve-application-property-values-from-a-word-processing-document) +- [Retrieve property values from a Word document by using the Open XML API](how-to-retrieve-application-property-values-from-a-word-processing-document.md) - [Set a custom property in a word processing document](how-to-set-a-custom-property-in-a-word-processing-document.md) From 455e7761f002316b32295a4756a0c3e005d1f240 Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Mon, 5 Feb 2024 11:57:56 -0800 Subject: [PATCH 003/103] closes #231 --- ...-add-text-to-a-word-processing-document.md | 105 ++++++------------ .../word/open_and_add_text_to/cs/Program.cs | 20 +++- .../word/open_and_add_text_to/vb/Program.vb | 36 +++++- 3 files changed, 83 insertions(+), 78 deletions(-) diff --git a/docs/word/how-to-open-and-add-text-to-a-word-processing-document.md b/docs/word/how-to-open-and-add-text-to-a-word-processing-document.md index b18ef6dd..a14babce 100644 --- a/docs/word/how-to-open-and-add-text-to-a-word-processing-document.md +++ b/docs/word/how-to-open-and-add-text-to-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: 02/05/2024 ms.localizationpriority: high --- # Open and add text to a word processing document @@ -24,66 +24,51 @@ document. -------------------------------------------------------------------------------- ## How to Open and Add Text to a Document + The Open XML SDK helps you create Word processing document structure -and content using strongly-typed classes that correspond to **WordprocessingML** elements. This topic shows how +and content using strongly-typed classes that correspond to `WordprocessingML` elements. This topic shows how to use the classes in the Open XML SDK to open a Word processing document and add text to it. In addition, this topic introduces the -basic document structure of a **WordprocessingML** document, the associated XML +basic document structure of a `WordprocessingML` document, the associated XML elements, and their corresponding Open XML SDK classes. -------------------------------------------------------------------------------- ## Create a WordprocessingDocument Object + 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. When you create the instance from the document, you can then obtain access to the main document part that contains the text of the document. The text in the main document part is represented -in the package as XML using **WordprocessingML** markup. +in the package as XML using `WordprocessingML` markup. -To create the class instance from the document you call one of the **Open** methods. Several are provided, each with a -different signature. The sample code in this topic uses the [Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) method with a -signature that requires two parameters. The first parameter takes a full +To create the class instance from the document you call one of the `Open` methods. Several are provided, each with a +different signature. The sample code in this topic uses the method with a signature that requires two parameters. The first parameter takes a full path string that represents the document to open. The second parameter -is either **true** or **false** and represents whether you want the file to +is either `true` or `false` and represents whether you want the file to be opened for editing. Changes you make to the document will not be -saved if this parameter is **false**. +saved if this parameter is `false`. -The following code example calls the **Open** -method. +The following code example calls the `Open` method. ### [C#](#tab/cs-0) -```csharp - // Open a WordprocessingDocument for editing using the filepath. - WordprocessingDocument wordprocessingDocument = - WordprocessingDocument.Open(filepath, true); -``` - +[!code-csharp[](../../samples/word/open_and_add_text_to/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - ' Open a WordprocessingDocument for editing using the filepath. - Dim wordprocessingDocument As WordprocessingDocument = WordprocessingDocument.Open(filepath, True) -``` +[!code-vb[](../../samples/word/open_and_add_text_to/vb/Program.vb#snippet1)] *** When you have opened the Word document package, you can add text to the -main document part. To access the body of the main document part, assign -a reference to the existing document body, as shown in the following -code example. +main document part. To access the body of the main document part, create +any missing elements and assign a reference to the document body, +as shown in the following code example. ### [C#](#tab/cs-1) -```csharp - // Assign a reference to the existing document body. - Body body = wordprocessingDocument.MainDocumentPart.Document.Body; -``` - +[!code-csharp[](../../samples/word/open_and_add_text_to/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-1) -```vb - ' Assign a reference to the existing document body. - Dim body As Body = wordprocessingDocument.MainDocumentPart.Document.Body -``` +[!code-vb[](../../samples/word/open_and_add_text_to/vb/Program.vb#snippet2)] *** @@ -94,66 +79,46 @@ code example. -------------------------------------------------------------------------------- ## Generate the WordprocessingML Markup to Add the Text When you have access to the body of the main document part, add text by -adding instances of the **Paragraph**, **Run**, and **Text** -classes. This generates the required WordprocessingML markup. The -following code example adds the paragraph, run and text. +adding instances of the , , +and classes. +This generates the required WordprocessingML markup. The +following code example adds the paragraph. ### [C#](#tab/cs-2) -```csharp - // Add new text. - Paragraph para = body.AppendChild(new Paragraph()); - Run run = para.AppendChild(new Run()); - run.AppendChild(new Text(txt)); -``` - +[!code-csharp[](../../samples/word/open_and_add_text_to/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-2) -```vb - ' Add new text. - Dim para As Paragraph = body.AppendChild(New Paragraph()) - Dim run As Run = para.AppendChild(New Run()) - run.AppendChild(New Text(txt)) -``` + +[!code-vb[](../../samples/word/open_and_add_text_to/vb/Program.vb#snippet3)] *** -------------------------------------------------------------------------------- ## Sample Code -The example **OpenAndAddTextToWordDocument** +The example `OpenAndAddTextToWordDocument` method shown here can be used to open a Word document and append some text using the Open XML SDK. To call this method, pass a full path -filename as the first parameter and the text to add as the second. For -example, the following code example opens the Letter.docx file in the -Public Documents folder and adds text to it. +filename as the first parameter and the text to add as the second. ### [C#](#tab/cs-3) -```csharp - string strDoc = @"C:\Users\Public\Documents\Letter.docx"; - string strTxt = "Append text in body - OpenAndAddTextToWordDocument"; - OpenAndAddTextToWordDocument(strDoc, strTxt); -``` - +[!code-csharp[](../../samples/word/open_and_add_text_to/cs/Program.cs#snippet4)] ### [Visual Basic](#tab/vb-3) -```vb - Dim strDoc As String = "C:\Users\Public\Documents\Letter.docx" - Dim strTxt As String = "Append text in body - OpenAndAddTextToWordDocument" - OpenAndAddTextToWordDocument(strDoc, strTxt) -``` +[!code-vb[](../../samples/word/open_and_add_text_to/vb/Program.vb#snippet4)] *** Following is the complete sample code in both C\# and Visual Basic. -Notice that the **OpenAndAddTextToWordDocument** method does not -include an explicit call to **Save**. That is +Notice that the `OpenAndAddTextToWordDocument` method does not +include an explicit call to `Save`. That is because the AutoSave feature is on by default and has not been disabled -in the call to the **Open** method through use -of **OpenSettings**. +in the call to the `Open` method through use +of `OpenSettings`. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/open_and_add_text_to/cs/Program.cs)] +[!code-csharp[](../../samples/word/open_and_add_text_to/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/open_and_add_text_to/vb/Program.vb)] +[!code-vb[](../../samples/word/open_and_add_text_to/vb/Program.vb#snippet0)] -------------------------------------------------------------------------------- ## See also diff --git a/samples/word/open_and_add_text_to/cs/Program.cs b/samples/word/open_and_add_text_to/cs/Program.cs index 007cef97..bd6e85d8 100644 --- a/samples/word/open_and_add_text_to/cs/Program.cs +++ b/samples/word/open_and_add_text_to/cs/Program.cs @@ -1,12 +1,11 @@ - +// using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System; -OpenAndAddTextToWordDocument(args[0], args[1]); - static void OpenAndAddTextToWordDocument(string filepath, string txt) { + // // Open a WordprocessingDocument for editing using the filepath. WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filepath, true); @@ -14,18 +13,31 @@ static void OpenAndAddTextToWordDocument(string filepath, string txt) { throw new ArgumentNullException(nameof(wordprocessingDocument)); } + // + // // Assign a reference to the existing document body. MainDocumentPart mainDocumentPart = wordprocessingDocument.MainDocumentPart ?? wordprocessingDocument.AddMainDocumentPart(); mainDocumentPart.Document ??= new Document(); mainDocumentPart.Document.Body ??= mainDocumentPart.Document.AppendChild(new Body()); Body body = wordprocessingDocument.MainDocumentPart!.Document!.Body!; + // + // // Add new text. Paragraph para = body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); run.AppendChild(new Text(txt)); + // - // Dispose the handle explicitly. + // There is no using block, so Dispose the handle explicitly. wordprocessingDocument.Dispose(); } +// + +// +string file = args[0]; +string txt = args[1]; + +OpenAndAddTextToWordDocument(args[0], args[1]); +// diff --git a/samples/word/open_and_add_text_to/vb/Program.vb b/samples/word/open_and_add_text_to/vb/Program.vb index 747a60f8..d8dc105f 100644 --- a/samples/word/open_and_add_text_to/vb/Program.vb +++ b/samples/word/open_and_add_text_to/vb/Program.vb @@ -1,3 +1,4 @@ +' Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Wordprocessing @@ -5,22 +6,49 @@ Imports DocumentFormat.OpenXml.Wordprocessing Module MyModule Sub Main(args As String()) + ' + Dim file As String = args(0) + Dim txt As String = args(1) + + OpenAndAddTextToWordDocument(file, txt) + ' End Sub Public Sub OpenAndAddTextToWordDocument(ByVal filepath As String, ByVal txt As String) + + ' ' Open a WordprocessingDocument for editing using the filepath. - Dim wordprocessingDocument As WordprocessingDocument = - WordprocessingDocument.Open(filepath, True) + Dim wordprocessingDocument As WordprocessingDocument = WordprocessingDocument.Open(filepath, True) + + If wordprocessingDocument Is Nothing Then + Throw New ArgumentNullException(NameOf(wordprocessingDocument)) + End If + ' + ' ' Assign a reference to the existing document body. + Dim mainDocumentPart As MainDocumentPart = If(wordprocessingDocument.MainDocumentPart, wordprocessingDocument.AddMainDocumentPart()) + + If wordprocessingDocument.MainDocumentPart.Document Is Nothing Then + wordprocessingDocument.MainDocumentPart.Document = New Document() + End If + + If wordprocessingDocument.MainDocumentPart.Document.Body Is Nothing Then + wordprocessingDocument.MainDocumentPart.Document.Body = New Body() + End If + Dim body As Body = wordprocessingDocument.MainDocumentPart.Document.Body + ' + ' ' Add new text. Dim para As Paragraph = body.AppendChild(New Paragraph) Dim run As Run = para.AppendChild(New Run) run.AppendChild(New Text(txt)) + ' - ' Dispose the handle explicitly. + ' There is not using, so Dispose the handle explicitly. wordprocessingDocument.Dispose() End Sub -End Module \ No newline at end of file +End Module +' From 00a87e65ee6dd97bd8a2e64578c321b7c3692d89 Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Mon, 5 Feb 2024 13:51:10 -0800 Subject: [PATCH 004/103] closes #230 --- ...-word-processing-document-from-a-stream.md | 87 +++++-------------- samples/word/open_from_a_stream/cs/Program.cs | 21 ++++- samples/word/open_from_a_stream/vb/Program.vb | 31 ++++++- 3 files changed, 72 insertions(+), 67 deletions(-) diff --git a/docs/word/how-to-open-a-word-processing-document-from-a-stream.md b/docs/word/how-to-open-a-word-processing-document-from-a-stream.md index 729c6443..c436959d 100644 --- a/docs/word/how-to-open-a-word-processing-document-from-a-stream.md +++ b/docs/word/how-to-open-a-word-processing-document-from-a-stream.md @@ -11,7 +11,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 02/05/2024 ms.localizationpriority: high --- # Open a word processing document from a stream @@ -47,31 +47,22 @@ XML package contains some number of parts. At a minimum, a method.Several `Open` methods are provided, each with a different +signature. The sample code in this topic uses the `Open` method with a signature that requires two parameters. The first parameter takes a handle to the stream from which -you want to open the document. The second parameter is either **true** or **false** and +you want to open the document. The second parameter is either `true` or `false` and represents whether the stream is opened for editing. -The following code example calls the **Open** +The following code example calls the `Open` method. ### [C#](#tab/cs-0) -```csharp - // Open a WordProcessingDocument based on a stream. - WordprocessingDocument wordprocessingDocument = - WordprocessingDocument.Open(stream, true); -``` - +[!code-csharp[](../../samples/word/open_from_a_stream/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - ' Open a WordProcessingDocument based on a stream. - Dim wordprocessingDocument As WordprocessingDocument = _ - WordprocessingDocument.Open(stream, True) -``` +[!code-vb[](../../samples/word/open_from_a_stream/vb/Program.vb#snippet1)] *** @@ -81,85 +72,55 @@ method. When you open the Word document package, you can add text to the main document part. To access the body of the main document part you assign a -reference to the existing document body, as shown in the following code -segment. +reference to the document body, as shown in the following code segment. ### [C#](#tab/cs-1) -```csharp - // Assign a reference to the existing document body. - Body body = wordprocessingDocument.MainDocumentPart.Document.Body; -``` - +[!code-csharp[](../../samples/word/open_from_a_stream/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-1) -```vb - ' Assign a reference to the existing document body. - Dim body As Body = wordprocessingDocument.MainDocumentPart.Document.Body -``` +[!code-vb[](../../samples/word/open_from_a_stream/vb/Program.vb#snippet2)] *** When you access to the body of the main document part, add text by -adding instances of the **Paragraph**, **Run**, and **Text** -classes. This generates the required **WordprocessingML** markup. The following lines from +adding instances of the , +, and +classes. This generates the required `WordprocessingML` markup. The following lines from the sample code add the paragraph, run, and text. ### [C#](#tab/cs-2) -```csharp - // Add new text. - Paragraph para = body.AppendChild(new Paragraph()); - Run run = para.AppendChild(new Run()); - run.AppendChild(new Text(txt)); -``` - +[!code-csharp[](../../samples/word/open_from_a_stream/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-2) -```vb - ' Add new text. - Dim para As Paragraph = body.AppendChild(New Paragraph()) - Dim run As Run = para.AppendChild(New Run()) - run.AppendChild(New Text(txt)) -``` +[!code-vb[](../../samples/word/open_from_a_stream/vb/Program.vb#snippet3)] *** ## Sample Code -The example **OpenAndAddToWordprocessingStream** method shown +The example `OpenAndAddToWordprocessingStream` method shown here can be used to open a Word document from an already open stream and append some text using the Open XML SDK. You can call it by passing a handle to an open stream as the first parameter and the text to add as the second. For example, the following code example opens the -Word13.docx file in the Public Documents folder and adds text to it. +file specified in the first argument and adds text from the second argument to it. ### [C#](#tab/cs-3) -```csharp - string strDoc = @"C:\Users\Public\Public Documents\Word13.docx"; - string txt = "Append text in body - OpenAndAddToWordprocessingStream"; - Stream stream = File.Open(strDoc, FileMode.Open); - OpenAndAddToWordprocessingStream(stream, txt); - stream.Close(); -``` - +[!code-csharp[](../../samples/word/open_from_a_stream/cs/Program.cs#snippet4)] ### [Visual Basic](#tab/vb-3) -```vb - Dim strDoc As String = "C:\Users\Public\Documents\Word13.docx" - Dim txt As String = "Append text in body - OpenAndAddToWordprocessingStream" - Dim stream As Stream = File.Open(strDoc, FileMode.Open) - OpenAndAddToWordprocessingStream(stream, txt) - stream.Close() -``` +[!code-vb[](../../samples/word/open_from_a_stream/vb/Program.vb#snippet4)] *** > [!NOTE] -> Notice that the **OpenAddAddToWordprocessingStream** method does not close the stream passed to it. The calling code must do that. +> Notice that the `OpenAddAddToWordprocessingStream` method does not close the stream passed to it. The calling code must do that +> by wrapping the method call in a `using` statement or explicitly calling Dispose. Following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/open_from_a_stream/cs/Program.cs)] +[!code-csharp[](../../samples/word/open_from_a_stream/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/open_from_a_stream/vb/Program.vb)] +[!code-vb[](../../samples/word/open_from_a_stream/vb/Program.vb#snippet0)] ## See also diff --git a/samples/word/open_from_a_stream/cs/Program.cs b/samples/word/open_from_a_stream/cs/Program.cs index 48645198..60326a64 100644 --- a/samples/word/open_from_a_stream/cs/Program.cs +++ b/samples/word/open_from_a_stream/cs/Program.cs @@ -1,4 +1,4 @@ - +// using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System.IO; @@ -6,21 +6,38 @@ static void OpenAndAddToWordprocessingStream(Stream stream, string txt) { + // // Open a WordProcessingDocument based on a stream. WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(stream, true); + // - // Assign a reference to the existing document body. + // + // Assign a reference to the document body. MainDocumentPart mainDocumentPart = wordprocessingDocument.MainDocumentPart ?? wordprocessingDocument.AddMainDocumentPart(); mainDocumentPart.Document ??= new Document(); Body body = mainDocumentPart.Document.Body ?? mainDocumentPart.Document.AppendChild(new Body()); + // + // // Add new text. Paragraph para = body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); run.AppendChild(new Text(txt)); + // // Dispose the document handle. wordprocessingDocument.Dispose(); // Caller must close the stream. } +// + +// +string filePath = args[0]; +string txt = args[1]; + +using (FileStream fileStream = new FileStream(filePath, FileMode.Open)) +{ + OpenAndAddToWordprocessingStream(fileStream, txt); +} +// diff --git a/samples/word/open_from_a_stream/vb/Program.vb b/samples/word/open_from_a_stream/vb/Program.vb index d439eb85..4a6cda00 100644 --- a/samples/word/open_from_a_stream/vb/Program.vb +++ b/samples/word/open_from_a_stream/vb/Program.vb @@ -1,3 +1,4 @@ +' Imports System.IO Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Wordprocessing @@ -6,23 +7,49 @@ Imports DocumentFormat.OpenXml.Wordprocessing Module MyModule Sub Main(args As String()) + ' + Dim filePath As String = args(0) + Dim txt As String = args(1) + + Using fileStream As FileStream = New FileStream(filePath, FileMode.Open) + OpenAndAddToWordprocessingStream(fileStream, txt) + End Using + ' End Sub Public Sub OpenAndAddToWordprocessingStream(ByVal stream As Stream, ByVal txt As String) + + ' ' Open a WordProcessingDocument based on a stream. Dim wordprocessingDocument As WordprocessingDocument = WordprocessingDocument.Open(stream, True) + ' + + ' + ' Assign a reference to the document body. + Dim mainDocumentPart As MainDocumentPart = If(wordprocessingDocument.MainDocumentPart, wordprocessingDocument.AddMainDocumentPart()) + + If wordprocessingDocument.MainDocumentPart.Document Is Nothing Then + wordprocessingDocument.MainDocumentPart.Document = New Document() + End If + + If wordprocessingDocument.MainDocumentPart.Document.Body Is Nothing Then + wordprocessingDocument.MainDocumentPart.Document.Body = New Body() + End If - ' Assign a reference to the existing document body. Dim body As Body = wordprocessingDocument.MainDocumentPart.Document.Body + ' + ' ' Add new text. Dim para As Paragraph = body.AppendChild(New Paragraph) Dim run As Run = para.AppendChild(New Run) run.AppendChild(New Text(txt)) + ' ' Dispose the document handle. wordprocessingDocument.Dispose() ' Caller must close the stream. End Sub -End Module \ No newline at end of file +End Module +' From 45cd9948d340a1b26bc23eb44de2f8a53b011b2d Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Tue, 6 Feb 2024 12:12:27 -0800 Subject: [PATCH 005/103] Extract Code Snippets from MD Files (#309) --- docs/includes/iso-iec-29500-2-link.md | 1 + ...en-text-from-a-word-processing-document.md | 155 +++----- ...footers-from-a-word-processing-document.md | 197 ++-------- ...he-header-in-a-word-processing-document.md | 31 +- ...les-parts-in-a-word-processing-document.md | 207 +++------- ...-values-from-a-word-processing-document.md | 70 +--- ...omments-from-a-word-processing-document.md | 87 +---- ...-property-in-a-word-processing-document.md | 365 ++---------------- samples/word/remove_hidden_text/cs/Program.cs | 76 ++-- samples/word/remove_hidden_text/vb/Program.vb | 62 +-- .../cs/Program.cs | 34 +- .../vb/Program.vb | 34 +- samples/word/replace_the_header/cs/Program.cs | 18 +- samples/word/replace_the_header/vb/Program.vb | 10 +- .../replace_the_styles_parts/cs/Program.cs | 69 +++- .../replace_the_styles_parts/vb/Program.vb | 66 +++- .../cs/Program.cs | 14 +- .../vb/Program.vb | 26 +- samples/word/retrieve_comments/cs/Program.cs | 12 +- samples/word/retrieve_comments/vb/Program.vb | 24 +- .../word/set_a_custom_property/cs/Program.cs | 45 ++- .../word/set_a_custom_property/vb/Program.vb | 40 +- 22 files changed, 606 insertions(+), 1037 deletions(-) create mode 100644 docs/includes/iso-iec-29500-2-link.md diff --git a/docs/includes/iso-iec-29500-2-link.md b/docs/includes/iso-iec-29500-2-link.md new file mode 100644 index 00000000..ea311344 --- /dev/null +++ b/docs/includes/iso-iec-29500-2-link.md @@ -0,0 +1 @@ +[ISO/IEC 29500-2](https://www.iso.org/standard/77818.html) \ No newline at end of file diff --git a/docs/word/how-to-remove-hidden-text-from-a-word-processing-document.md b/docs/word/how-to-remove-hidden-text-from-a-word-processing-document.md index 718ab2ef..5a29ca50 100644 --- a/docs/word/how-to-remove-hidden-text-from-a-word-processing-document.md +++ b/docs/word/how-to-remove-hidden-text-from-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: 02/02/2024 ms.localizationpriority: medium --- # Remove hidden text from a word processing document @@ -21,100 +21,26 @@ Office to programmatically remove hidden text from a word processing document. - ---------------------------------------------------------------------------------- -## Getting a WordprocessingDocument Object -To open an existing document, you instantiate the class as shown in the -following **using** statement. In the same -statement, you open the word processing file with the specified -*fileName* by using the **Open** method, with -the Boolean parameter set to **true** in order -to enable editing the document. - -### [C#](#tab/cs-0) -```csharp - using (WordprocessingDocument doc = - WordprocessingDocument.Open(fileName, true)) - { - // Insert other code here. - } -``` - -### [Visual Basic](#tab/vb-0) -```vb - Using wdDoc As WordprocessingDocument = _ - WordprocessingDocument.Open(filepath, True) - ' Insert other code here. - End Using -``` -*** - - -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 doc. 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**. - - -------------------------------------------------------------------------------- -## 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." - -```xml - - - - - Example text. - - - - -``` - -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. - -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. +[!include[Word Structure](../includes/word/structure.md)] --------------------------------------------------------------------------------- ## Structure of the Vanish Element -The **vanish** element plays an important role in hiding the text in a -Word file. The **Hidden** formatting property is a toggle property, + +The `vanish` element plays an important role in hiding the text in a +Word file. The `Hidden` formatting property is a toggle property, which means that its behavior differs between using it within a style definition and using it as direct formatting. When used as part of a style definition, setting this property toggles its current state. -Setting it to **false** (or an equivalent) +Setting it to `false` (or an equivalent) results in keeping the current setting unchanged. However, when used as -direct formatting, setting it to **true** or -**false** sets the absolute state of the +direct formatting, setting it to `true` or +`false` sets the absolute state of the resulting property. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification -introduces the **vanish** element. +introduces the `vanish` element. > **vanish (Hidden Text)** > @@ -126,7 +52,7 @@ introduces the **vanish** element. > This formatting property is a *toggle property* (§17.7.3). > > If this element is not present, the default value is to leave the -> formatting applied at previous level in the *style hierarchy* .If this +> formatting applied at previous level in the *style hierarchy*. If this > element is never applied in the style hierarchy, then this text shall > not be hidden when displayed in a document. > @@ -154,44 +80,59 @@ The following XML schema segment defines the contents of this element. ``` -The **val** property in the code above is a binary value that can be -turned on or off. If given a value of **on**, **1**, or **true** the property is turned on. If given the -value **off**, **0**, or **false** the property +The `val` property in the code above is a binary value that can be +turned on or off. If given a value of `on`, `1`, or `true` the property is turned on. If given the +value `off`, `0`, or `false` the property is turned off. +## How the Code Works --------------------------------------------------------------------------------- -## Sample Code -The following code example shows how to remove all of the hidden text -from a document. You can call the method, WDDeleteHiddenText, by using -the following call as an example to delete the hidden text from a file -named "Word14.docx." - -### [C#](#tab/cs-1) -```csharp - string docName = @"C:\Users\Public\Documents\Word14.docx"; - WDDeleteHiddenText(docName); -``` +The `WDDeleteHiddenText` method works with the document you specify and removes all of the `run` elements that are hidden and removes extra `vanish` elements. The code starts by opening the +document, using the method and indicating that the +document should be opened for read/write access (the final true +parameter). Given the open document, the code uses the property to navigate to +the main document, storing the reference in a variable. -### [Visual Basic](#tab/vb-1) -```vb - Dim docName As String = "C:\Users\Public\Documents\Word14.docx" - WDDeleteHiddenText(docName) -``` +### [C#](#tab/cs) +[!code-csharp[](../../samples/word/remove_hidden_text/cs/Program.cs#snippet1)] +### [Visual Basic](#tab/vb) +[!code-vb[](../../samples/word/remove_hidden_text/vb/Program.vb#snippet1)] *** +## Get a List of Vanish Elements + +The code first checks that `doc.MainDocumentPart` and `doc.MainDocumentPart.Document.Body` are not null and throws an exception if one is missing. Then uses the passing it the type to get an `IEnumerable` of the `Vanish` elements and casts them to a list. + +### [C#](#tab/cs) +[!code-csharp[](../../samples/word/remove_hidden_text/cs/Program.cs#snippet2)] +### [Visual Basic](#tab/vb) +[!code-vb[](../../samples/word/remove_hidden_text/vb/Program.vb#snippet2)] +*** + +## Remove Runs with Hidden Text and Extra Vanish Elements + +To remove the hidden text we next loop over the `List` of `Vanish` elements. The `Vanish` element is a child of the but `RunProperties` can be a child of a or xref:DocumentFormat.OpenXml.Wordprocessing.ParagraphProperties>, so we get the parent and grandparent of each `Vanish` and check its type. Then if the grandparent is a `Run` we remove that run and if not +we we remove the `Vanish` child elements from the parent. + +### [C#](#tab/cs) +[!code-csharp[](../../samples/word/remove_hidden_text/cs/Program.cs#snippet3)] +### [Visual Basic](#tab/vb) +[!code-vb[](../../samples/word/remove_hidden_text/vb/Program.vb#snippet3)] +*** +-------------------------------------------------------------------------------- +## Sample Code > [!NOTE] -> This example assumes that the file Word14.docx contains some hidden text. In order to hide part of the file text, select it, and click CTRL+D to show the **Font** dialog box. Select the **Hidden** box and click **OK**. +> This example assumes that the file being opened contains some hidden text. In order to hide part of the file text, select it, and click CTRL+D to show the **Font** dialog box. Select the **Hidden** box and click **OK**. Following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/remove_hidden_text/cs/Program.cs)] +[!code-csharp[](../../samples/word/remove_hidden_text/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/remove_hidden_text/vb/Program.vb)] +[!code-vb[](../../samples/word/remove_hidden_text/vb/Program.vb#snippet0)] -------------------------------------------------------------------------------- ## See also diff --git a/docs/word/how-to-remove-the-headers-and-footers-from-a-word-processing-document.md b/docs/word/how-to-remove-the-headers-and-footers-from-a-word-processing-document.md index 254bd21e..c2aa5f44 100644 --- a/docs/word/how-to-remove-the-headers-and-footers-from-a-word-processing-document.md +++ b/docs/word/how-to-remove-the-headers-and-footers-from-a-word-processing-document.md @@ -12,38 +12,33 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 06/28/2021 +ms.date: 02/02/2024 ms.localizationpriority: medium --- # Remove the headers and footers from a word processing document This topic shows how to use the classes in the Open XML SDK for Office to programmatically remove all headers and footers in a word -processing document. It contains an example **RemoveHeadersAndFooters** method to illustrate this +processing document. It contains an example `RemoveHeadersAndFooters` method to illustrate this task. ## RemoveHeadersAndFooters Method -You can use the **RemoveHeadersAndFooters** +You can use the `RemoveHeadersAndFooters` method to remove all header and footer information from a word processing document. Be aware that you must not only delete the header and footer parts from the document storage, you must also delete the references to those parts from the document too. The sample code -demonstrates both steps in the operation. The **RemoveHeadersAndFooters** method accepts a single +demonstrates both steps in the operation. The `RemoveHeadersAndFooters` method accepts a single parameter, a string that indicates the path of the file that you want to modify. ### [C#](#tab/cs-0) -```csharp - public static void RemoveHeadersAndFooters(string filename) -``` - +[!code-csharp[](../../samples/word/remove_the_headers_and_footers/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - Public Sub RemoveHeadersAndFooters(ByVal filename As String) -``` +[!code-vb[](../../samples/word/remove_the_headers_and_footers/vb/Program.vb#snippet1)] *** @@ -56,46 +51,26 @@ contains the file name of the document that you want to modify as shown in the following code example. ### [C#](#tab/cs-1) -```csharp - RemoveHeadersAndFooters(@"C:\Users\Public\Documents\Headers.docx"); -``` - +[!code-csharp[](../../samples/word/remove_the_headers_and_footers/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-1) -```vb - RemoveHeadersAndFooters("C:\Users\Public\Documents\Headers.docx") -``` +[!code-vb[](../../samples/word/remove_the_headers_and_footers/vb/Program.vb#snippet2)] *** ## How the Code Works -The **RemoveHeadersAndFooters** method works +The `RemoveHeadersAndFooters` method works with the document you specify, deleting all of the header and footer parts and references to those parts. The code starts by opening the -document, using the [Open](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) method and indicating that the +document, using the method and indicating that the document should be opened for read/write access (the final true -parameter). Given the open document, the code uses the [MainDocumentPart](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.maindocumentpart) property to navigate to -the main document, storing the reference in a variable named **docPart**. +parameter). Given the open document, the code uses the property to navigate to +the main document, storing the reference in a variable named `docPart`. ### [C#](#tab/cs-2) -```csharp - // Given a document name, remove all of the headers and footers - // from the document. - using (WordprocessingDocument doc = - WordprocessingDocument.Open(filename, true)) - { - // Code removed here... - } -``` - +[!code-csharp[](../../samples/word/remove_the_headers_and_footers/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-2) -```vb - ' Given a document name, remove all of the headers and footers - ' from the document. - Using doc = WordprocessingDocument.Open(filename, True) - ' Code removed here... - End Using -``` +[!code-vb[](../../samples/word/remove_the_headers_and_footers/vb/Program.vb#snippet3)] *** @@ -103,38 +78,17 @@ the main document, storing the reference in a variable named **docPart**. Given a reference to the document part, the code next determines if it has any work to do─that is, if the document contains any headers or -footers. To decide, the code calls the **Count** method of both the [HeaderParts](/dotnet/api/documentformat.openxml.packaging.maindocumentpart.headerparts) and [FooterParts](/dotnet/api/documentformat.openxml.packaging.maindocumentpart.footerparts) properties of the document +footers. To decide, the code calls the `Count` method of both the and + properties of the document part, and if either returns a value greater than 0, the code continues. -Be aware that the **HeaderParts** and **FooterParts** properties each return an -[IEnumerable](/dotnet/api/system.collections.generic.ienumerable-1) of -[HeaderPart](/dotnet/api/system.collections.generic.ienumerable-1) or [FooterPart](/dotnet/api/documentformat.openxml.packaging.footerpart) objects, respectively. +Be aware that the `HeaderParts` and `FooterParts` properties each return an + of + or objects, respectively. ### [C#](#tab/cs-3) -```csharp - // Get a reference to the main document part. - var docPart = doc.MainDocumentPart; - - // Count the header and footer parts and continue if there - // are any. - if (docPart.HeaderParts.Count() > 0 || - docPart.FooterParts.Count() > 0) - { - // Code removed here... - } -``` - +[!code-csharp[](../../samples/word/remove_the_headers_and_footers/cs/Program.cs#snippet4)] ### [Visual Basic](#tab/vb-3) -```vb - ' Get a reference to the main document part. - Dim docPart = doc.MainDocumentPart - - ' Count the header and footer parts and continue if there - ' are any. - If (docPart.HeaderParts.Count > 0) Or - (docPart.FooterParts.Count > 0) Then - ' Code removed here... - End If -``` +[!code-vb[](../../samples/word/remove_the_headers_and_footers/vb/Program.vb#snippet4)] *** @@ -142,29 +96,20 @@ Be aware that the **HeaderParts** and **FooterParts** properties each return an Given a collection of references to header and footer parts, you could write code to delete each one individually, but that is not necessary -because of the Open XML SDK. Instead, you can call the [DeleteParts\](/dotnet/api/documentformat.openxml.packaging.openxmlpartcontainer.deleteparts) method, passing in the +because of the Open XML SDK. Instead, you can call the method, passing in the collection of parts to be deleted─this simple method provides a shortcut for deleting a collection of parts. Therefore, the following few lines of code take the place of the loop that you would otherwise have to write yourself. ### [C#](#tab/cs-4) -```csharp - // Remove the header and footer parts. - docPart.DeleteParts(docPart.HeaderParts); - docPart.DeleteParts(docPart.FooterParts); -``` - +[!code-csharp[](../../samples/word/remove_the_headers_and_footers/cs/Program.cs#snippet5)] ### [Visual Basic](#tab/vb-4) -```vb - ' Remove the header and footer parts. - docPart.DeleteParts(docPart.HeaderParts) - docPart.DeleteParts(docPart.FooterParts) -``` +[!code-vb[](../../samples/word/remove_the_headers_and_footers/vb/Program.vb#snippet5)] *** -## Work with the Document Content +## Delete the Header and Footer References At this point, the code has deleted the header and footer parts, but the document still contains orphaned references to those parts. Before the @@ -172,104 +117,36 @@ orphaned references can be removed, the code must retrieve a reference to the content of the document (that is, to the XML content contained within the main document part). Later, after the changes are made, the code must ensure that they persist by explicitly saving them. Between -these two operations, the code must delete the orphaned references, as -shown in the section that follows the following code example. - -### [C#](#tab/cs-5) -```csharp - // Get a reference to the root element of the main - // document part. - Document document = docPart.Document; - // Code removed here... - // Save the changes. - document.Save(); -``` - -### [Visual Basic](#tab/vb-5) -```vb - ' Get a reference to the root element of the main - ' document part. - Dim document As Document = docPart.Document - ' Code removed here... - ' Save the changes. - document.Save() -``` -*** - - -## Delete the Header and Footer References +these two operations, the code must delete the orphaned references. To remove the stranded references, the code first retrieves a collection -of HeaderReference elements, converts the collection to a List, and then -loops through the collection, calling the [Remove](/dotnet/api/documentformat.openxml.openxmlelement.remove) method for each element found. Note -that the code converts the **IEnumerable** -returned by the [Descendants](/dotnet/api/documentformat.openxml.openxmlelement.descendants) method into a List so that it -can delete items from the list, and that the [HeaderReference](/dotnet/api/documentformat.openxml.wordprocessing.headerreference) type that is provided by -the Open XML SDK makes it easy to refer to elements of type **HeaderReference** in the XML content. (Without that +of HeaderReference elements, converts the collection to a `List`, and then +loops through the collection, calling the method for each element found. Note +that the code converts the `IEnumerable` +returned by the method into a `List` so that it +can delete items from the list, and that the type that is provided by +the Open XML SDK makes it easy to refer to elements of type `HeaderReference` in the XML content. (Without that additional help, you would have to work with the details of the XML content directly.) Once it has removed all the headers, the code repeats the operation with the footer elements. ### [C#](#tab/cs-6) -```csharp - // Remove all references to the headers and footers. - - // First, create a list of all descendants of type - // HeaderReference. Then, navigate the list and call - // Remove on each item to delete the reference. - var headers = - document.Descendants().ToList(); - foreach (var header in headers) - { - header.Remove(); - } - - // First, create a list of all descendants of type - // FooterReference. Then, navigate the list and call - // Remove on each item to delete the reference. - var footers = - document.Descendants().ToList(); - foreach (var footer in footers) - { - footer.Remove(); - } -``` - +[!code-csharp[](../../samples/word/remove_the_headers_and_footers/cs/Program.cs#snippet6)] ### [Visual Basic](#tab/vb-6) -```vb - ' Remove all references to the headers and footers. - - ' First, create a list of all descendants of type - ' HeaderReference. Then, navigate the list and call - ' Remove on each item to delete the reference. - Dim headers = _ - document.Descendants(Of HeaderReference).ToList() - For Each header In headers - header.Remove() - Next - - ' First, create a list of all descendants of type - ' FooterReference. Then, navigate the list and call - ' Remove on each item to delete the reference. - Dim footers = _ - document.Descendants(Of FooterReference).ToList() - For Each footer In footers - footer.Remove() - Next -``` +[!code-vb[](../../samples/word/remove_the_headers_and_footers/vb/Program.vb#snippet6)] *** ## Sample Code -The following is the complete **RemoveHeadersAndFooters** code sample in C\# and +The following is the complete `RemoveHeadersAndFooters` code sample in C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/remove_the_headers_and_footers/cs/Program.cs)] +[!code-csharp[](../../samples/word/remove_the_headers_and_footers/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/remove_the_headers_and_footers/vb/Program.vb)] +[!code-vb[](../../samples/word/remove_the_headers_and_footers/vb/Program.vb#snippet0)] ## See also diff --git a/docs/word/how-to-replace-the-header-in-a-word-processing-document.md b/docs/word/how-to-replace-the-header-in-a-word-processing-document.md index 0cf9c24e..346403ae 100644 --- a/docs/word/how-to-replace-the-header-in-a-word-processing-document.md +++ b/docs/word/how-to-replace-the-header-in-a-word-processing-document.md @@ -12,7 +12,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 06/28/2021 +ms.date: 02/01/2024 ms.localizationpriority: high --- # Replace the header in a word processing document @@ -28,10 +28,8 @@ programmatically. In this example you are going to delete the header part from the target file and create another header part. You are also going to delete the reference to the existing header and create a reference to the new -header. Therefore it is useful to familarize yourself with headers and -the header reference element. The following information from the -[!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification introduces the header reference element. +header. Therefore it is useful to familiarize yourself with headers and +the header reference element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the header reference element. ## headerReference (Header Reference) @@ -102,7 +100,7 @@ using the following WordprocessingML: The resulting section shall use the header part with relationship id **rId3** for the first page, the header part with relationship id **rId2** for all subsequent even -pages, and the header part with relationship id **rId5** for all subsequent odd pages. *end example*] +pages, and the header part with relationship id **rId5** for all subsequent odd pages. *end example* © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] @@ -110,33 +108,24 @@ pages, and the header part with relationship id **rId5** for all subsequent odd The following code example shows how to replace the header in a word processing document with the header from another word processing -document. To call the method, **AddHeaderFromTo**, you can use the following code +document. To call the method, `AddHeaderFromTo`, you can use the following code segment as an example. ### [C#](#tab/cs-0) -```csharp - string filepathFrom = @"C:\Users\Public\Documents\Word15a.docx"; - string filepathTo=@"C:\Users\Public\Documents\Word15b.docx"; - AddHeaderFromTo(filepathFrom, filepathTo); -``` - +[!code-csharp[](../../samples/word/replace_the_header/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - Dim filepathFrom As String = "C:\Users\Public\Documents\word15a.docx" - Dim filepathTo As String = "C:\Users\Public\Documents\Word15b.docx" - AddHeaderFromTo(filepathFrom, filepathTo) -``` +[!code-vb[](../../samples/word/replace_the_header/vb/Program.vb#snippet1)] *** Following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/replace_the_header/cs/Program.cs)] +[!code-csharp[](../../samples/word/replace_the_header/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/replace_the_header/vb/Program.vb)] +[!code-vb[](../../samples/word/replace_the_header/vb/Program.vb#snippet0)] ## 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/word/how-to-replace-the-styles-parts-in-a-word-processing-document.md b/docs/word/how-to-replace-the-styles-parts-in-a-word-processing-document.md index 06511740..8e0431d8 100644 --- a/docs/word/how-to-replace-the-styles-parts-in-a-word-processing-document.md +++ b/docs/word/how-to-replace-the-styles-parts-in-a-word-processing-document.md @@ -12,7 +12,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 06/28/2021 +ms.date: 02/01/2024 ms.localizationpriority: medium --- # Replace the styles parts in a word processing document @@ -20,8 +20,8 @@ ms.localizationpriority: medium This topic shows how to use the classes in the Open XML SDK for Office to programmatically replace the styles in a word processing document with the styles from another word processing document. It -contains an example **ReplaceStyles** method to illustrate this task, as -well as the **ReplaceStylesPart** and **ExtractStylesPart** supporting +contains an example `ReplaceStyles` method to illustrate this task, as +well as the `ReplaceStylesPart` and `ExtractStylesPart` supporting methods. @@ -37,18 +37,19 @@ a particular content type, and can contain content equal to the content of an external XML file, binary file, image file, and so on, depending on the type. The standard that defines how Open XML documents are stored in .zip files is called the Open Packaging Conventions. For more -information about the Open Packaging Conventions, see [ISO/IEC 29500-2](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.md?csnumber=51459). +information about the Open Packaging Conventions, see [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-2-link.md)]. Styles are stored in dedicated parts within a word processing document package. A Microsoft Word 2010 document contains a single styles part. -Microsoft Word 2013 adds a second stylesWithEffects part. The following +later versions of Microsoft Word add a second stylesWithEffects part. The following image from the Document Explorer in the Open XML SDK Productivity -Tool for Microsoft Office shows the document parts in a sample Word 2013 +Tool for Microsoft Office shows the document parts in a sample Word 2013+ document that contains styles. Figure 1. Styles parts in a word processing document ![Styles parts in a word processing document.](../media/OpenXmlCon_HowToReplaceStyles_Fig1.gif) + In order to provide for "round-tripping" a document from Word 2013+ to Word 2010 and back, Word 2013+ maintains both the original styles part and the new styles part. (The Office Open XML File Formats specification @@ -63,27 +64,23 @@ styles parts. ## ReplaceStyles Method -You can use the **ReplaceStyles** sample method to replace the styles in +You can use the `ReplaceStyles` sample method to replace the styles in a word processing document with the styles in another word processing -document. The **ReplaceStyles** method accepts two parameters: the first +document. The `ReplaceStyles` method accepts two parameters: the first parameter contains a string that indicates the path of the file that contains the styles to extract. The second parameter contains a string that indicates the path of the file to which to copy the styles, effectively completely replacing the styles. ### [C#](#tab/cs-0) -```csharp - public static void ReplaceStyles(string fromDoc, string toDoc) -``` +[!code-csharp[](../../samples/word/replace_the_styles_parts/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - Public Sub ReplaceStyles(fromDoc As String, toDoc As String) -``` +[!code-vb[](../../samples/word/replace_the_styles_parts/vb/Program.vb#snippet1)] *** -The complete code listing for the **ReplaceStyles** method and its supporting methods +The complete code listing for the `ReplaceStyles` method and its supporting methods can be found in the [Sample Code](#sample-code) section. --------------------------------------------------------------------------------- @@ -99,18 +96,9 @@ have been replaced, and consequently the appearance of the text in the document will reflect the new styles. ### [C#](#tab/cs-1) -```csharp - const string fromDoc = @"C:\Users\Public\Documents\StylesFrom.docx"; - const string toDoc = @"C:\Users\Public\Documents\StylesTo.docx"; - ReplaceStyles(fromDoc, toDoc); -``` - +[!code-csharp[](../../samples/word/replace_the_styles_parts/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-1) -```vb - Const fromDoc As String = "C:\Users\Public\Documents\StylesFrom.docx" - Const toDoc As String = "C:\Users\Public\Documents\StylesTo.docx" - ReplaceStyles(fromDoc, toDoc) -``` +[!code-vb[](../../samples/word/replace_the_styles_parts/vb/Program.vb#snippet2)] *** @@ -120,35 +108,22 @@ document will reflect the new styles. The code extracts and replaces the styles part first, and then the stylesWithEffects part second, and relies on two supporting methods to -do most of the work. The **ExtractStylesPart** +do most of the work. The `ExtractStylesPart` method has the job of extracting the content of the styles or -stylesWithEffects part, and placing it in an -[XDocument](/dotnet/api/system.xml.linq.xdocument) -object. The **ReplaceStylesPart** method takes -the object created by **ExtractStylesPart** and +stylesWithEffects part, and placing it in an +object. The `ReplaceStylesPart` method takes +the object created by `ExtractStylesPart` and uses its content to replace the styles or stylesWithEffects part in the target document. ### [C#](#tab/cs-2) -```csharp - // Extract and replace the styles part. - var node = ExtractStylesPart(fromDoc, false); - if (node != null) - ReplaceStylesPart(toDoc, node, false); -``` - +[!code-csharp[](../../samples/word/replace_the_styles_parts/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-2) -```vb - ' Extract and replace the styles part. - Dim node = ExtractStylesPart(fromDoc, False) - If node IsNot Nothing Then - ReplaceStylesPart(toDoc, node, False) - End If -``` +[!code-vb[](../../samples/word/replace_the_styles_parts/vb/Program.vb#snippet3)] *** -The final parameter in the signature for either the **ExtractStylesPart** or the **ReplaceStylesPart** method determines whether the +The final parameter in the signature for either the `ExtractStylesPart` or the `ReplaceStylesPart` method determines whether the styles part or the stylesWithEffects part is employed. A value of false indicates that you want to extract and replace the styles part. The absence of a value (the parameter is optional), or a value of true (the @@ -156,44 +131,27 @@ default), means that you want to extract and replace the stylesWithEffects part. ### [C#](#tab/cs-3) -```csharp - // Extract and replace the stylesWithEffects part. To fully support - // round-tripping from Word 2013+ to Word 2010, you should - // replace this part, as well. - node = ExtractStylesPart(fromDoc); - if (node != null) - ReplaceStylesPart(toDoc, node); - return; -``` - +[!code-csharp[](../../samples/word/replace_the_styles_parts/cs/Program.cs#snippet4)] ### [Visual Basic](#tab/vb-3) -```vb - ' Extract and replace the stylesWithEffects part. To fully support - ' round-tripping from Word 2013+ to Word 2010, you should - ' replace this part, as well. - node = ExtractStylesPart(fromDoc, True) - If node IsNot Nothing Then - ReplaceStylesPart(toDoc, node, True) - End If -``` +[!code-vb[](../../samples/word/replace_the_styles_parts/vb/Program.vb#snippet4)] *** -For more information about the **ExtractStylesPart** method, see [the associated sample](how-to-extract-styles-from-a-word-processing-document.md). The -following section explains the **ReplaceStylesPart** method. +For more information about the `ExtractStylesPart` method, see [the associated sample](how-to-extract-styles-from-a-word-processing-document.md). The +following section explains the `ReplaceStylesPart` method. --------------------------------------------------------------------------------- ## ReplaceStylesPart Method -The **ReplaceStylesPart** method can be used to +The `ReplaceStylesPart` method can be used to replace the styles or styleWithEffects part in a document, given an -**XDocument** instance that contains the same +`XDocument` instance that contains the same part for a Word 2010 or Word 2013+ document (as shown in the sample code -earlier in this topic, the **ExtractStylesPart** method can be used to obtain -that instance). The **ReplaceStylesPart** +earlier in this topic, the `ExtractStylesPart` method can be used to obtain +that instance). The `ReplaceStylesPart` method accepts three parameters: the first parameter contains a string that indicates the path to the file that you want to modify. The second -parameter contains an **XDocument** object that +parameter contains an `XDocument` object that contains the styles or stylesWithEffect part from another word processing document, and the third indicates whether you want to replace the styles part, or the stylesWithEffects part (as shown in the sample @@ -202,17 +160,9 @@ for Word 2013+ documents, replacing each part with the corresponding part from a source document). ### [C#](#tab/cs-4) -```csharp - public static void ReplaceStylesPart(string fileName, XDocument newStyles, - bool setStylesWithEffectsPart = true) -``` - +[!code-csharp[](../../samples/word/replace_the_styles_parts/cs/Program.cs#snippet5)] ### [Visual Basic](#tab/vb-4) -```vb - Public Sub ReplaceStylesPart( - ByVal fileName As String, ByVal newStyles As XDocument, - Optional ByVal setStylesWithEffectsPart As Boolean = True) -``` +[!code-vb[](../../samples/word/replace_the_styles_parts/vb/Program.vb#snippet5)] *** @@ -220,69 +170,34 @@ from a source document). ## How the ReplaceStylesPart Code Works -The **ReplaceStylesPart** method examines the +The `ReplaceStylesPart` method examines the document you specify, looking for the styles or stylesWithEffects part. -If the requested part exists, the method saves the supplied **XDocument** into the selected part. +If the requested part exists, the method saves the supplied `XDocument` into the selected part. -The code starts by opening the document by using the **[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). Given the open document, the code -uses the **[MainDocumentPart](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.maindocumentpart)** property to navigate to -the main document part, and then prepares a variable named **stylesPart** to hold a reference to the styles part. +The code starts by opening the document by using the method and indicating that the +document should be open for read/write access (the final `true` parameter). Given the open document, the code +uses the property to navigate to +the main document part, and then prepares a variable named `stylesPart` to hold a reference to the styles part. ### [C#](#tab/cs-5) -```csharp - // Open the document for write access and get a reference. - using (var document = - WordprocessingDocument.Open(fileName, true)) - { - // Get a reference to the main document part. - var docPart = document.MainDocumentPart; - - // Assign a reference to the appropriate part to the - // stylesPart variable. - StylesPart stylesPart = null; -``` - +[!code-csharp[](../../samples/word/replace_the_styles_parts/cs/Program.cs#snippet6)] ### [Visual Basic](#tab/vb-5) -```vb - ' Open the document for write access and get a reference. - Using document = WordprocessingDocument.Open(fileName, True) - - ' Get a reference to the main document part. - Dim docPart = document.MainDocumentPart - - ' Assign a reference to the appropriate part to the - ' stylesPart variable. - Dim stylesPart As StylesPart = Nothing -``` +[!code-vb[](../../samples/word/replace_the_styles_parts/vb/Program.vb#snippet6)] *** - --------------------------------------------------------------------------------- ## Find the Correct Styles Part The code next retrieves a reference to the requested styles part, using -the **setStylesWithEffectsPart** Boolean +the `setStylesWithEffectsPart` Boolean parameter. Based on this value, the code retrieves a reference to the -requested styles part, and stores it in the **stylesPart** variable. +requested styles part, and stores it in the `stylesPart` variable. ### [C#](#tab/cs-6) -```csharp - if (setStylesWithEffectsPart) - stylesPart = docPart.StylesWithEffectsPart; - else - stylesPart = docPart.StyleDefinitionsPart; -``` - +[!code-csharp[](../../samples/word/replace_the_styles_parts/cs/Program.cs#snippet7)] ### [Visual Basic](#tab/vb-6) -```vb - If setStylesWithEffectsPart Then - stylesPart = docPart.StylesWithEffectsPart - Else - stylesPart = docPart.StyleDefinitionsPart - End If -``` +[!code-vb[](../../samples/word/replace_the_styles_parts/vb/Program.vb#snippet7)] *** @@ -291,33 +206,17 @@ requested styles part, and stores it in the **stylesPart** variable. ## Save the Part Contents Assuming that the requested part exists, the code must save the entire -contents of the **XDocument** passed to the -method to the part. Each part provides a **[GetStream](/dotnet/api/documentformat.openxml.packaging.openxmlpart.getstream)** method, which returns a Stream. -The code passes the Stream instance to the constructor of the -[StreamWriter](/dotnet/api/system.io.streamwriter.-ctor) +contents of the `XDocument` passed to the +method to the part. Each part provides a method, which returns a . +The code passes the Stream instance to the constructor of the class, creating a stream writer around the stream of the part. Finally, -the code calls the -[Save](/dotnet/api/system.xml.linq.xdocument.save) method of +the code calls the method of the XDocument, saving its contents into the styles part. ### [C#](#tab/cs-7) -```csharp - // If the part exists, populate it with the new styles. - if (stylesPart != null) - { - newStyles.Save(new StreamWriter(stylesPart.GetStream( - FileMode.Create, FileAccess.Write))); - } -``` - +[!code-csharp[](../../samples/word/replace_the_styles_parts/cs/Program.cs#snippet8)] ### [Visual Basic](#tab/vb-7) -```vb - ' If the part exists, populate it with the new styles. - If stylesPart IsNot Nothing Then - newStyles.Save(New StreamWriter( - stylesPart.GetStream(FileMode.Create, FileAccess.Write))) - End If -``` +[!code-vb[](../../samples/word/replace_the_styles_parts/vb/Program.vb#snippet8)] *** @@ -325,14 +224,14 @@ the XDocument, saving its contents into the styles part. ## Sample Code -The following is the complete **ReplaceStyles**, **ReplaceStylesPart**, and **ExtractStylesPart** methods in C\# and Visual +The following is the complete `ReplaceStyles`, `ReplaceStylesPart`, and `ExtractStylesPart` methods in C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/replace_the_styles_parts/cs/Program.cs)] +[!code-csharp[](../../samples/word/replace_the_styles_parts/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/replace_the_styles_parts/vb/Program.vb)] +[!code-vb[](../../samples/word/replace_the_styles_parts/vb/Program.vb#snippet0)] --------------------------------------------------------------------------------- diff --git a/docs/word/how-to-retrieve-application-property-values-from-a-word-processing-document.md b/docs/word/how-to-retrieve-application-property-values-from-a-word-processing-document.md index 56340afa..cc754d74 100644 --- a/docs/word/how-to-retrieve-application-property-values-from-a-word-processing-document.md +++ b/docs/word/how-to-retrieve-application-property-values-from-a-word-processing-document.md @@ -12,7 +12,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 06/28/2021 +ms.date: 01/31/2024 ms.localizationpriority: medium --- @@ -24,75 +24,31 @@ This topic shows how to use the classes in the Open XML SDK for Office to progra ## Retrieving Application Properties -To retrieve application document properties, you can retrieve the **ExtendedFilePropertiesPart** property of a object, and then retrieve the specific application property you need. To do this, you must first get a reference to the document, as shown in the following code. +To retrieve application document properties, you can retrieve the property of a object, and then retrieve the specific application property you need. To do this, you must first get a reference to the document, as shown in the following code. ### [C#](#tab/cs-0) -```csharp - const string FILENAME = "DocumentProperties.docx"; - - using (WordprocessingDocument document = - WordprocessingDocument.Open(FILENAME, false)) - { - // Code removed here… - } -``` - +[!code-csharp[](../../samples/word/retrieve_application_property_values/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - Private Const FILENAME As String = "DocumentProperties.docx" - - Using document As WordprocessingDocument = - WordprocessingDocument.Open(FILENAME, True) - ' Code removed here… - End Using -``` +[!code-vb[](../../samples/word/retrieve_application_property_values/vb/Program.vb#snippet1)] *** -Given the reference to the object, you can retrieve a reference to the **ExtendedFilePropertiesPart** property of the document. This object provides its own properties, each of which exposes one of the application document properties. +Given the reference to the object, you can retrieve a reference to the property of the document. This object provides its own properties, each of which exposes one of the application document properties. ### [C#](#tab/cs-1) -```csharp - var props = document.ExtendedFilePropertiesPart.Properties; -``` - +[!code-csharp[](../../samples/word/retrieve_application_property_values/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-1) -```vb - Dim props = document.ExtendedFilePropertiesPart.Properties -``` +[!code-vb[](../../samples/word/retrieve_application_property_values/vb/Program.vb#snippet2)] *** -Once you have the reference to the properties of **ExtendedFilePropertiesPart**, you can then retrieve any of the application properties, using simple code such as that shown -in the next example. Note that the code must confirm that the reference to each property isn't **null** before retrieving its **Text** property. Unlike core properties, -document properties aren't available if you (or the application) haven't specifically given them a value. +Once you have the reference to the properties of , you can then retrieve any of the application properties, using simple code such as that shown +in the next example. Note that the code must confirm that the reference to each property isn't `null` of `Nothing` before retrieving its `Text` property. Unlike core properties, document properties aren't available if you (or the application) haven't specifically given them a value. ### [C#](#tab/cs-2) -```csharp - if (props.Company != null) - Console.WriteLine("Company = " + props.Company.Text); - - if (props.Lines != null) - Console.WriteLine("Lines = " + props.Lines.Text); - - if (props.Manager != null) - Console.WriteLine("Manager = " + props.Manager.Text); -``` - +[!code-csharp[](../../samples/word/retrieve_application_property_values/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-2) -```vb - If props.Company IsNot Nothing Then - Console.WriteLine("Company = " & props.Company.Text) - End If - - If props.Lines IsNot Nothing Then - Console.WriteLine("Lines = " & props.Lines.Text) - End If - - If props.Manager IsNot Nothing Then - Console.WriteLine("Manager = " & props.Manager.Text) - End If -``` +[!code-vb[](../../samples/word/retrieve_application_property_values/vb/Program.vb#snippet3)] *** @@ -101,10 +57,10 @@ document properties aren't available if you (or the application) haven't specifi The following is the complete code sample in C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/retrieve_application_property_values/cs/Program.cs)] +[!code-csharp[](../../samples/word/retrieve_application_property_values/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/retrieve_application_property_values/vb/Program.vb)] +[!code-vb[](../../samples/word/retrieve_application_property_values/vb/Program.vb#snippet0)] ## See also diff --git a/docs/word/how-to-retrieve-comments-from-a-word-processing-document.md b/docs/word/how-to-retrieve-comments-from-a-word-processing-document.md index fc063dd6..c285d5ba 100644 --- a/docs/word/how-to-retrieve-comments-from-a-word-processing-document.md +++ b/docs/word/how-to-retrieve-comments-from-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/26/2024 ms.localizationpriority: medium --- # Retrieve comments from a word processing document @@ -25,40 +25,26 @@ part in a word processing document. -------------------------------------------------------------------------------- ## Open the Existing Document for Read-only Access To open an existing document, instantiate the class as shown in -the following **using** statement. In the same -statement, open the word processing file at the specified **fileName** by using the [Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) method. To open the -file for editing the Boolean parameter is set to **true**. In this example you just need to read the -file; therefore, you can open the file for read-only access by setting -the Boolean parameter to **false**. +the following `using` statement. In the same +statement, open the word processing file at the specified `fileName` by using the method. To open the file for editing the Boolean parameter is set to `true`. In this example you just need to read the file; therefore, you can open the file for read-only access by setting +the Boolean parameter to `false`. ### [C#](#tab/cs-0) -```csharp - using (WordprocessingDocument wordDoc = - WordprocessingDocument.Open(fileName, false)) - { - // Insert other code here. - } -``` - +[!code-csharp[](../../samples/word/retrieve_comments/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - Using wordDoc As WordprocessingDocument = WordprocessingDocument.Open(fileName, False) - ' Insert other code here. - End Using -``` +[!code-vb[](../../samples/word/retrieve_comments/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**. +The `using` statement provides a recommended alternative to the .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`. -------------------------------------------------------------------------------- ## Comments Element -The **comments** and **comment** elements are crucial to working with + +The `comments` and `comment` elements are crucial to working with comments in a word processing file. It is important in this code example to familiarize yourself with those elements. @@ -97,6 +83,7 @@ element. --------------------------------------------------------------------------------- ## Comment Element + The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the comment element. @@ -114,6 +101,7 @@ introduces the comment element. > Consider a document with text with an annotated comment as follows: ![Document text with annotated comment](../media/w-comment01.gif) + > This comment is represented by the following WordprocessingML > fragment. @@ -128,8 +116,7 @@ introduces the comment element. > © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] -The following XML schema segment defines the contents of the comment -element. +The following XML schema segment defines the contents of the comment element. ```xml @@ -146,57 +133,25 @@ element. -------------------------------------------------------------------------------- ## How the Sample Code Works -After you have opened the file for read-only access, you instantiate the -**WordprocessingCommentsPart** class. You can -then display the inner text of the **Comment** -element. +After you have opened the file for read-only access, you instantiate the class. You can +then display the inner text of the element. ### [C#](#tab/cs-1) -```csharp - foreach (Comment comment in commentsPart.Comments.Elements()) - { - Console.WriteLine(comment.InnerText); - } -``` - +[!code-csharp[](../../samples/word/retrieve_comments/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-1) -```vb - For Each comment As Comment In _ - commentsPart.Comments.Elements(Of Comment)() - Console.WriteLine(comment.InnerText) - Next -``` +[!code-vb[](../../samples/word/retrieve_comments/vb/Program.vb#snippet2)] *** - -------------------------------------------------------------------------------- ## Sample Code -The following code example shows how to retrieve comments that have been -inserted into a word processing document. To call the method **GetCommentsFromDocument** you can use the following -call, which retrieves comments from a file named "Word16.docx," as an -example. - -### [C#](#tab/cs-2) -```csharp - string fileName = @"C:\Users\Public\Documents\Word16.docx"; - GetCommentsFromDocument(fileName); -``` - -### [Visual Basic](#tab/vb-2) -```vb - Dim fileName As String = "C:\Users\Public\Documents\Word16.docx" - GetCommentsFromDocument(fileName) -``` -*** - The following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/retrieve_comments/cs/Program.cs)] +[!code-csharp[](../../samples/word/retrieve_comments/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/retrieve_comments/vb/Program.vb)] +[!code-vb[](../../samples/word/retrieve_comments/vb/Program.vb#snippet0)] -------------------------------------------------------------------------------- ## See also diff --git a/docs/word/how-to-set-a-custom-property-in-a-word-processing-document.md b/docs/word/how-to-set-a-custom-property-in-a-word-processing-document.md index cd601cbb..9900e28e 100644 --- a/docs/word/how-to-set-a-custom-property-in-a-word-processing-document.md +++ b/docs/word/how-to-set-a-custom-property-in-a-word-processing-document.md @@ -12,39 +12,19 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 06/28/2021 +ms.date: 01/26/2024 ms.localizationpriority: high --- # Set a custom property in a word processing document -This topic shows how to use the classes in the Open XML SDK for Office to programmatically set a custom property in a word processing document. It contains an example **SetCustomProperty** method to illustrate this task. +This topic shows how to use the classes in the Open XML SDK for Office to programmatically set a custom property in a word processing document. It contains an example `SetCustomProperty` method to illustrate this task. - - -The sample code also includes an enumeration that defines the possible types of custom properties. The **SetCustomProperty** method requires that you supply one of these values when you call the method. +The sample code also includes an enumeration that defines the possible types of custom properties. The `SetCustomProperty` method requires that you supply one of these values when you call the method. ### [C#](#tab/cs-0) -```csharp - public enum PropertyTypes : int - { - YesNo, - Text, - DateTime, - NumberInteger, - NumberDouble - } -``` - +[!code-csharp[](../../samples/word/set_a_custom_property/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - Public Enum PropertyTypes - YesNo - Text - DateTime - NumberInteger - NumberDouble - End Enum -``` +[!code-vb[](../../samples/word/set_a_custom_property/vb/Program.vb#snippet1)] *** @@ -84,11 +64,11 @@ If you examine the XML content, you will find the following: - Each property in the XML content includes a **pid** attribute, which must include an integer starting at 2 for the first property and incrementing for each successive property. - Each property tracks its type (in the figure, the **vt:lpwstr** and **vt:filetime** element names define the types for each property). -The sample method that is provided here includes the code that is required to create or modify a custom document property in a Microsoft Word 2010 or Microsoft Word 2013 document. You can find the complete code listing for the method in the [Sample Code](#sample-code) section. +The sample method that is provided here includes the code that is required to create or modify a custom document property in a Microsoft Word document. You can find the complete code listing for the method in the [Sample Code](#sample-code) section. ## SetCustomProperty Method -Use the **SetCustomProperty** method to set a custom property in a word processing document. The **SetCustomProperty** method accepts four parameters: +Use the `SetCustomProperty` method to set a custom property in a word processing document. The `SetCustomProperty` method accepts four parameters: - The name of the document to modify (string). @@ -99,64 +79,26 @@ Use the **SetCustomProperty** method to set a custom property in a word processi - The kind of property (one of the values in the **PropertyTypes** enumeration). ### [C#](#tab/cs-1) -```csharp - public static string SetCustomProperty( - string fileName, - string propertyName, - object propertyValue, - PropertyTypes propertyType) -``` - +[!code-csharp[](../../samples/word/set_a_custom_property/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-1) -```vb - Public Function SetCustomProperty( _ - ByVal fileName As String, - ByVal propertyName As String, _ - ByVal propertyValue As Object, - ByVal propertyType As PropertyTypes) As String -``` +[!code-vb[](../../samples/word/set_a_custom_property/vb/Program.vb#snippet2)] *** ## Calling the SetCustomProperty Method -The **SetCustomProperty** method enables you to set a custom property, and returns the current value of the property, if it exists. To call the sample method, pass the file name, property name, property value, and property type parameters. The following sample code shows an example. +The `SetCustomProperty` method enables you to set a custom property, and returns the current value of the property, if it exists. To call the sample method, pass the file name, property name, property value, and property type parameters. The following sample code shows an example. ### [C#](#tab/cs-2) -```csharp - const string fileName = @"C:\Users\Public\Documents\SetCustomProperty.docx"; - - Console.WriteLine("Manager = " + - SetCustomProperty(fileName, "Manager", "Peter", PropertyTypes.Text)); - - Console.WriteLine("Manager = " + - SetCustomProperty(fileName, "Manager", "Mary", PropertyTypes.Text)); - - Console.WriteLine("ReviewDate = " + - SetCustomProperty(fileName, "ReviewDate", - DateTime.Parse("12/21/2010"), PropertyTypes.DateTime)); -``` - +[!code-csharp[](../../samples/word/set_a_custom_property/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-2) -```vb - Const fileName As String = "C:\Users\Public\Documents\SetCustomProperty.docx" - - Console.WriteLine("Manager = " & - SetCustomProperty(fileName, "Manager", "Peter", PropertyTypes.Text)) - - Console.WriteLine("Manager = " & - SetCustomProperty(fileName, "Manager", "Mary", PropertyTypes.Text)) - - Console.WriteLine("ReviewDate = " & - SetCustomProperty(fileName, "ReviewDate", - #12/21/2010#, PropertyTypes.DateTime)) -``` +[!code-vb[](../../samples/word/set_a_custom_property/vb/Program.vb#snippet3)] *** After running this code, use the following procedure to view the custom properties from Word. -1. Open the **SetCustomProperty.docx** file in Word. +1. Open the .docx file in Word. 2. On the **File** tab, click **Info**. 3. Click **Properties**. 4. Click **Advanced Properties**. @@ -169,230 +111,59 @@ Figure 2. Custom Properties in the Advanced Properties dialog box ## How the Code Works -The **SetCustomProperty** method starts by setting up some internal variables. Next, it examines the information about the property, and creates a new [CustomDocumentProperty](/dotnet/api/documentformat.openxml.customproperties.customdocumentproperty) based on the parameters that you have specified. The code also maintains a variable named **propSet** to indicate whether it successfully created the new property object. This code verifies the -type of the property value, and then converts the input to the correct type, setting the appropriate property of the **CustomDocumentProperty** object. +The `SetCustomProperty` method starts by setting up some internal variables. Next, it examines the information about the property, and creates a new based on the parameters that you have specified. The code also maintains a variable named `propSet` to indicate whether it successfully created the new property object. This code verifies the +type of the property value, and then converts the input to the correct type, setting the appropriate property of the object. > [!NOTE] -> The **CustomDocumentProperty** type works much like a VBA Variant type. It maintains separate placeholders as properties for the various types of data it might contain. +> The type works much like a VBA Variant type. It maintains separate placeholders as properties for the various types of data it might contain. ### [C#](#tab/cs-3) -```csharp - string returnValue = null; - - var newProp = new CustomDocumentProperty(); - bool propSet = false; - - // Calculate the correct type. - switch (propertyType) - { - case PropertyTypes.DateTime: - - // Be sure you were passed a real date, - // and if so, format in the correct way. - // The date/time value passed in should - // represent a UTC date/time. - if ((propertyValue) is DateTime) - { - newProp.VTFileTime = - new VTFileTime(string.Format("{0:s}Z", - Convert.ToDateTime(propertyValue))); - propSet = true; - } - - break; - - case PropertyTypes.NumberInteger: - if ((propertyValue) is int) - { - newProp.VTInt32 = new VTInt32(propertyValue.ToString()); - propSet = true; - } - - break; - - case PropertyTypes.NumberDouble: - if (propertyValue is double) - { - newProp.VTFloat = new VTFloat(propertyValue.ToString()); - propSet = true; - } - - break; - - case PropertyTypes.Text: - newProp.VTLPWSTR = new VTLPWSTR(propertyValue.ToString()); - propSet = true; - - break; - - case PropertyTypes.YesNo: - if (propertyValue is bool) - { - // Must be lowercase. - newProp.VTBool = new VTBool( - Convert.ToBoolean(propertyValue).ToString().ToLower()); - propSet = true; - } - break; - } - - if (!propSet) - { - // If the code was not able to convert the - // property to a valid value, throw an exception. - throw new InvalidDataException("propertyValue"); - } -``` - +[!code-csharp[](../../samples/word/set_a_custom_property/cs/Program.cs#snippet4)] ### [Visual Basic](#tab/vb-3) -```vb - Dim returnValue As String = Nothing - - Dim newProp As New CustomDocumentProperty - Dim propSet As Boolean = False - - ' Calculate the correct type: - Select Case propertyType - - Case PropertyTypes.DateTime - ' Be sure you were passed a real date, - ' and if so, format in the correct way. - ' The date/time value passed in should - ' represent a UTC date/time. - If TypeOf (propertyValue) Is DateTime Then - newProp.VTFileTime = _ - New VTFileTime(String.Format("{0:s}Z", - Convert.ToDateTime(propertyValue))) - propSet = True - End If - - Case PropertyTypes.NumberInteger - If TypeOf (propertyValue) Is Integer Then - newProp.VTInt32 = New VTInt32(propertyValue.ToString()) - propSet = True - End If - - Case PropertyTypes.NumberDouble - If TypeOf propertyValue Is Double Then - newProp.VTFloat = New VTFloat(propertyValue.ToString()) - propSet = True - End If - - Case PropertyTypes.Text - newProp.VTLPWSTR = New VTLPWSTR(propertyValue.ToString()) - propSet = True - - Case PropertyTypes.YesNo - If TypeOf propertyValue Is Boolean Then - ' Must be lowercase. - newProp.VTBool = _ - New VTBool(Convert.ToBoolean(propertyValue).ToString().ToLower()) - propSet = True - End If - End Select - - If Not propSet Then - ' If the code was not able to convert the - ' property to a valid value, throw an exception. - Throw New InvalidDataException("propertyValue") - End If -``` +[!code-vb[](../../samples/word/set_a_custom_property/vb/Program.vb#snippet4)] *** - -At this point, if the code has not thrown an exception, you can assume that the property is valid, and the code sets the [FormatId](/dotnet/api/documentformat.openxml.customproperties.customdocumentproperty.formatid) and [Name](/dotnet/api/documentformat.openxml.customproperties.customdocumentproperty.name) properties of the new custom property. +At this point, if the code has not thrown an exception, you can assume that the property is valid, and the code sets the and properties of the new custom property. ### [C#](#tab/cs-4) -```csharp - // Now that you have handled the parameters, start - // working on the document. - newProp.FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"; - newProp.Name = propertyName; -``` - +[!code-csharp[](../../samples/word/set_a_custom_property/cs/Program.cs#snippet5)] ### [Visual Basic](#tab/vb-4) -```vb - ' Now that you have handled the parameters, start - ' working on the document. - newProp.FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" - newProp.Name = propertyName -``` +[!code-vb[](../../samples/word/set_a_custom_property/vb/Program.vb#snippet5)] *** ## Working with the Document -Given the **CustomDocumentProperty** object, the code next interacts with the document that you supplied in the parameters to the **SetCustomProperty** procedure. The code starts by opening the document in read/write mode by -using the [Open](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) method of the class. The code attempts to retrieve a reference to the custom file properties part by using the [CustomFilePropertiesPart](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.customfilepropertiespart) property of the document. +Given the object, the code next interacts with the document that you supplied in the parameters to the `SetCustomProperty` procedure. The code starts by opening the document in read/write mode by +using the method of the class. The code attempts to retrieve a reference to the custom file properties part by using the property of the document. ### [C#](#tab/cs-5) -```csharp - using (var document = WordprocessingDocument.Open(fileName, true)) - { - var customProps = document.CustomFilePropertiesPart; - // Code removed here... - } -``` - +[!code-csharp[](../../samples/word/set_a_custom_property/cs/Program.cs#snippet6)] ### [Visual Basic](#tab/vb-5) -```vb - Using document = WordprocessingDocument.Open(fileName, True) - Dim customProps = document.CustomFilePropertiesPart - ' Code removed here... - End Using -``` +[!code-vb[](../../samples/word/set_a_custom_property/vb/Program.vb#snippet6)] *** If the code cannot find a custom properties part, it creates a new part, and adds a new set of properties to the part. ### [C#](#tab/cs-6) -```csharp - if (customProps == null) - { - // No custom properties? Add the part, and the - // collection of properties now. - customProps = document.AddCustomFilePropertiesPart(); - customProps.Properties = - new DocumentFormat.OpenXml.CustomProperties.Properties(); - } -``` - +[!code-csharp[](../../samples/word/set_a_custom_property/cs/Program.cs#snippet7)] ### [Visual Basic](#tab/vb-6) -```vb - If customProps Is Nothing Then - ' No custom properties? Add the part, and the - ' collection of properties now. - customProps = document.AddCustomFilePropertiesPart - customProps.Properties = New Properties - End If -``` +[!code-vb[](../../samples/word/set_a_custom_property/vb/Program.vb#snippet7)] *** -Next, the code retrieves a reference to the [Properties](/dotnet/api/documentformat.openxml.packaging.customfilepropertiespart.properties) property of the custom +Next, the code retrieves a reference to the property of the custom properties part (that is, a reference to the properties themselves). If the code had to create a new custom properties part, you know that this reference is not null. However, for existing custom properties parts, it -is possible, although highly unlikely, that the **Properties** property will be null. If so, the code +is possible, although highly unlikely, that the property will be null. If so, the code cannot continue. ### [C#](#tab/cs-7) -```csharp - var props = customProps.Properties; - if (props != null) - { - // Code removed here... - } -``` - +[!code-csharp[](../../samples/word/set_a_custom_property/cs/Program.cs#snippet8)] ### [Visual Basic](#tab/vb-7) -```vb - Dim props = customProps.Properties - If props IsNot Nothing Then - ' Code removed here... - End If -``` +[!code-vb[](../../samples/word/set_a_custom_property/vb/Program.vb#snippet8)] *** @@ -407,33 +178,9 @@ and then re-create the element. The code uses a simple LINQ query to find the first match for the property name. ### [C#](#tab/cs-8) -```csharp - var prop = - props.Where( - p => ((CustomDocumentProperty)p).Name.Value - == propertyName).FirstOrDefault(); - - // Does the property exist? If so, get the return value, - // and then delete the property. - if (prop != null) - { - returnValue = prop.InnerText; - prop.Remove(); - } -``` - +[!code-csharp[](../../samples/word/set_a_custom_property/cs/Program.cs#snippet9)] ### [Visual Basic](#tab/vb-8) -```vb - Dim prop = props. - Where(Function(p) CType(p, CustomDocumentProperty). - Name.Value = propertyName).FirstOrDefault() - ' Does the property exist? If so, get the return value, - ' and then delete the property. - If prop IsNot Nothing Then - returnValue = prop.InnerText - prop.Remove() - End If -``` +[!code-vb[](../../samples/word/set_a_custom_property/vb/Program.vb#snippet9)] *** @@ -441,63 +188,35 @@ Now, you will know for sure that the custom property part exists, a property tha 1. Appends the new property as a child of the properties collection. -2. Loops through all the existing properties, and sets the **pid** attribute to increasing values, starting at 2. +2. Loops through all the existing properties, and sets the **pid** attribute to increasing values, starting at 2. 3. Saves the part. ### [C#](#tab/cs-9) -```csharp - // Append the new property, and - // fix up all the property ID values. - // The PropertyId value must start at 2. - props.AppendChild(newProp); - int pid = 2; - foreach (CustomDocumentProperty item in props) - { - item.PropertyId = pid++; - } - props.Save(); -``` - +[!code-csharp[](../../samples/word/set_a_custom_property/cs/Program.cs#snippet10)] ### [Visual Basic](#tab/vb-9) -```vb - ' Append the new property, and - ' fix up all the property ID values. - ' The PropertyId value must start at 2. - props.AppendChild(newProp) - Dim pid As Integer = 2 - For Each item As CustomDocumentProperty In props - item.PropertyId = pid - pid += 1 - Next - props.Save() -``` +[!code-vb[](../../samples/word/set_a_custom_property/vb/Program.vb#snippet10)] *** Finally, the code returns the stored original property value. ### [C#](#tab/cs-10) -```csharp - return returnValue; -``` - +[!code-csharp[](../../samples/word/set_a_custom_property/cs/Program.cs#snippet11)] ### [Visual Basic](#tab/vb-10) -```vb - Return returnValue -``` +[!code-vb[](../../samples/word/set_a_custom_property/vb/Program.vb#snippet11)] *** - ## Sample Code -The following is the complete **SetCustomProperty** code sample in C\# and Visual Basic. +The following is the complete `SetCustomProperty` code sample in C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/set_a_custom_property/cs/Program.cs)] +[!code-csharp[](../../samples/word/set_a_custom_property/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/set_a_custom_property/vb/Program.vb)] +[!code-vb[](../../samples/word/set_a_custom_property/vb/Program.vb#snippet0)] +*** ## See also diff --git a/samples/word/remove_hidden_text/cs/Program.cs b/samples/word/remove_hidden_text/cs/Program.cs index 88fd856d..5224553b 100644 --- a/samples/word/remove_hidden_text/cs/Program.cs +++ b/samples/word/remove_hidden_text/cs/Program.cs @@ -1,67 +1,53 @@ +// using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; using System; -using System.IO; -using System.Xml; +using System.Collections.Generic; +using System.Linq; -WDDeleteHiddenText(args[0]); static void WDDeleteHiddenText(string docName) { // Given a document name, delete all the hidden text. - const string wordmlNamespace = "https://schemas.openxmlformats.org/wordprocessingml/2006/main"; - using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(docName, true)) + // + using (WordprocessingDocument doc = WordprocessingDocument.Open(docName, true)) { - // Manage namespaces to perform XPath queries. - NameTable nt = new NameTable(); - XmlNamespaceManager nsManager = new XmlNamespaceManager(nt); - nsManager.AddNamespace("w", wordmlNamespace); + // - if (wdDoc.MainDocumentPart is null || wdDoc.MainDocumentPart.Document.Body is null) + // + if (doc.MainDocumentPart is null || doc.MainDocumentPart.Document.Body is null) { throw new ArgumentNullException("MainDocumentPart and/or Body is null."); } - // Get the document part from the package. - // Load the XML in the document part into an XmlDocument instance. - XmlDocument xdoc = new XmlDocument(nt); - using (Stream stream = wdDoc.MainDocumentPart.GetStream()) + // Get a list of all the Vanish elements + List vanishes = doc.MainDocumentPart.Document.Body.Descendants().ToList(); + // + + // + // Loop over the list of Vanish elements + foreach (Vanish vanish in vanishes) { - xdoc.Load(stream); - XmlNodeList? hiddenNodes = xdoc.SelectNodes("//w:vanish", nsManager); + var parent = vanish?.Parent; + var grandparent = parent?.Parent; - if (hiddenNodes is null) + // If the grandparent is a Run remove it + if (grandparent is Run) { - return; // No hidden text. + grandparent.Remove(); } - - foreach (System.Xml.XmlNode hiddenNode in hiddenNodes) + // If it's not a run remove the Vanish + else if (parent is not null) { - if (hiddenNode.ParentNode is null || hiddenNode.ParentNode.ParentNode is null || hiddenNode.ParentNode.ParentNode.ParentNode is null) - { - continue; - } - - XmlNode topNode = hiddenNode.ParentNode.ParentNode; - XmlNode topParentNode = topNode.ParentNode; - topParentNode.RemoveChild(topNode); - - if (topParentNode.ParentNode is null) - { - continue; - } - - if (!topParentNode.HasChildNodes) - { - topParentNode.ParentNode.RemoveChild(topParentNode); - } + parent.RemoveAllChildren(); } } - - using (Stream stream2 = wdDoc.MainDocumentPart.GetStream(FileMode.Create, FileAccess.Write)) - { - // Save the document XML back to its document part. - xdoc.Save(stream2); - } + // } -} \ No newline at end of file +} +// + +string fileName = args[0]; + +WDDeleteHiddenText(fileName); diff --git a/samples/word/remove_hidden_text/vb/Program.vb b/samples/word/remove_hidden_text/vb/Program.vb index d62a94d2..597b25d5 100644 --- a/samples/word/remove_hidden_text/vb/Program.vb +++ b/samples/word/remove_hidden_text/vb/Program.vb @@ -1,39 +1,49 @@ -Imports System.IO -Imports System.Xml +' Imports DocumentFormat.OpenXml.Packaging +Imports DocumentFormat.OpenXml.Wordprocessing Module Program Sub Main(args As String()) + Dim fileName As String = args(0) + + WDDeleteHiddenText(fileName) End Sub - Public Sub WDDeleteHiddenText(ByVal docName As String) + Public Sub WDDeleteHiddenText(ByVal fileName As String) ' Given a document name, delete all the hidden text. - Const wordmlNamespace As String = "https://schemas.openxmlformats.org/wordprocessingml/2006/main" - - Using wdDoc As WordprocessingDocument = WordprocessingDocument.Open(docName, True) - ' Manage namespaces to perform XPath queries. - Dim nt As New NameTable() - Dim nsManager As New XmlNamespaceManager(nt) - nsManager.AddNamespace("w", wordmlNamespace) - - ' Get the document part from the package. - ' Load the XML in the document part into an XmlDocument instance. - Dim xdoc As New XmlDocument(nt) - xdoc.Load(wdDoc.MainDocumentPart.GetStream()) - Dim hiddenNodes As XmlNodeList = xdoc.SelectNodes("//w:vanish", nsManager) - For Each hiddenNode As System.Xml.XmlNode In hiddenNodes - Dim topNode As XmlNode = hiddenNode.ParentNode.ParentNode - Dim topParentNode As XmlNode = topNode.ParentNode - topParentNode.RemoveChild(topNode) - If Not (topParentNode.HasChildNodes) Then - topParentNode.ParentNode.RemoveChild(topParentNode) + + ' + Using doc As WordprocessingDocument = WordprocessingDocument.Open(fileName, True) + ' + + ' + If doc.MainDocumentPart Is Nothing Or doc.MainDocumentPart.Document.Body Is Nothing Then + Throw New ArgumentNullException("MainDocumentPart and/or Body is Nothing.") + End If + + 'Get a list of all the Vanish elements + Dim vanishes As List(Of Vanish) = doc.MainDocumentPart.Document.Body.Descendants(Of Vanish).ToList() + ' + + ' + ' Loop over the list of Vanish elements + For Each vanish In vanishes + Dim parent = vanish.Parent + Dim grandparent = parent.Parent + + ' If the grandparent is a Run remove it + If TypeOf grandparent Is Run Then + grandparent.Remove() + + ' If it's not a run remove the Vanish + ElseIf parent IsNot Nothing Then + parent.RemoveAllChildren(Of Vanish)() End If Next - - ' Save the document XML back to its document part. - xdoc.Save(wdDoc.MainDocumentPart.GetStream(FileMode.Create, FileAccess.Write)) + ' End Using End Sub -End Module \ No newline at end of file +End Module +' diff --git a/samples/word/remove_the_headers_and_footers/cs/Program.cs b/samples/word/remove_the_headers_and_footers/cs/Program.cs index bd18865f..e741fb71 100644 --- a/samples/word/remove_the_headers_and_footers/cs/Program.cs +++ b/samples/word/remove_the_headers_and_footers/cs/Program.cs @@ -1,17 +1,22 @@ +// using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System; using System.Linq; -RemoveHeadersAndFooters(args[0]); // Remove all of the headers and footers from a document. +// static void RemoveHeadersAndFooters(string filename) +// { + // // Given a document name, remove all of the headers and footers // from the document. using (WordprocessingDocument doc = WordprocessingDocument.Open(filename, true)) + // { + // if (doc.MainDocumentPart is null) { throw new ArgumentNullException("MainDocumentPart is null."); @@ -22,13 +27,17 @@ static void RemoveHeadersAndFooters(string filename) // Count the header and footer parts and continue if there // are any. - if (docPart.HeaderParts.Count() > 0 || - docPart.FooterParts.Count() > 0) + if (docPart.HeaderParts.Count() > 0 || docPart.FooterParts.Count() > 0) { + // + + // // Remove the header and footer parts. docPart.DeleteParts(docPart.HeaderParts); docPart.DeleteParts(docPart.FooterParts); + // + // // Get a reference to the root element of the main // document part. Document document = docPart.Document; @@ -38,8 +47,8 @@ static void RemoveHeadersAndFooters(string filename) // First, create a list of all descendants of type // HeaderReference. Then, navigate the list and call // Remove on each item to delete the reference. - var headers = - document.Descendants().ToList(); + var headers = document.Descendants().ToList(); + foreach (var header in headers) { header.Remove(); @@ -48,8 +57,8 @@ static void RemoveHeadersAndFooters(string filename) // First, create a list of all descendants of type // FooterReference. Then, navigate the list and call // Remove on each item to delete the reference. - var footers = - document.Descendants().ToList(); + var footers = document.Descendants().ToList(); + foreach (var footer in footers) { footer.Remove(); @@ -57,6 +66,15 @@ static void RemoveHeadersAndFooters(string filename) // Save the changes. document.Save(); + // } } -} \ No newline at end of file +} +// + +// +string filename = args[0]; + +RemoveHeadersAndFooters(filename); +// + diff --git a/samples/word/remove_the_headers_and_footers/vb/Program.vb b/samples/word/remove_the_headers_and_footers/vb/Program.vb index e8ea0b53..14ea979f 100644 --- a/samples/word/remove_the_headers_and_footers/vb/Program.vb +++ b/samples/word/remove_the_headers_and_footers/vb/Program.vb @@ -1,31 +1,49 @@ +' Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Spreadsheet Imports DocumentFormat.OpenXml.Wordprocessing Module Program Sub Main(args As String()) + ' + Dim filename As String = args(0) + + RemoveHeadersAndFooters(filename) + ' End Sub ' To remove all of the headers and footers in a document. + ' Public Sub RemoveHeadersAndFooters(ByVal filename As String) + ' + ' ' Given a document name, remove all of the headers and footers ' from the document. Using doc = WordprocessingDocument.Open(filename, True) + ' + + ' + If doc.MainDocumentPart Is Nothing Then + Throw New ArgumentNullException("MainDocumentPart is Nothing") + End If ' Get a reference to the main document part. Dim docPart = doc.MainDocumentPart ' Count the header and footer parts and continue if there ' are any. - If (docPart.HeaderParts.Count > 0) Or - (docPart.FooterParts.Count > 0) Then + If (docPart.HeaderParts.Count > 0) Or (docPart.FooterParts.Count > 0) Then + ' + ' ' Remove the header and footer parts. docPart.DeleteParts(docPart.HeaderParts) docPart.DeleteParts(docPart.FooterParts) + ' + ' ' Get a reference to the root element of the main ' document part. Dim document As Document = docPart.Document @@ -35,8 +53,8 @@ Module Program ' First, create a list of all descendants of type ' HeaderReference. Then, navigate the list and call ' Remove on each item to delete the reference. - Dim headers = - document.Descendants(Of HeaderReference).ToList() + Dim headers = document.Descendants(Of HeaderReference).ToList() + For Each header In headers header.Remove() Next @@ -44,8 +62,8 @@ Module Program ' First, create a list of all descendants of type ' FooterReference. Then, navigate the list and call ' Remove on each item to delete the reference. - Dim footers = - document.Descendants(Of FooterReference).ToList() + Dim footers = document.Descendants(Of FooterReference).ToList() + For Each footer In footers footer.Remove() Next @@ -53,6 +71,8 @@ Module Program ' Save the changes. document.Save() End If + ' End Using End Sub -End Module \ No newline at end of file +End Module +' diff --git a/samples/word/replace_the_header/cs/Program.cs b/samples/word/replace_the_header/cs/Program.cs index aac671ab..37329ad3 100644 --- a/samples/word/replace_the_header/cs/Program.cs +++ b/samples/word/replace_the_header/cs/Program.cs @@ -1,16 +1,16 @@ +// using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System; using System.Collections.Generic; using System.Linq; -AddHeaderFromTo(args[0], args[1]); -static void AddHeaderFromTo(string filepathFrom, string filepathTo) +static void AddHeaderFromTo(string fromFile, string toFile) { // Replace header in target document with header of source document. - using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(filepathTo, true)) - using (WordprocessingDocument wdDocSource = WordprocessingDocument.Open(filepathFrom, true)) + using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(toFile, true)) + using (WordprocessingDocument wdDocSource = WordprocessingDocument.Open(fromFile, true)) { if (wdDocSource.MainDocumentPart is null || wdDocSource.MainDocumentPart.HeaderParts is null) { @@ -60,4 +60,12 @@ static void AddHeaderFromTo(string filepathFrom, string filepathTo) sectPr.PrependChild(new HeaderReference() { Id = rId }); } } -} \ No newline at end of file +} +// + +// +string fromFile = args[0]; +string toFile = args[1]; + +AddHeaderFromTo(fromFile, toFile); +// \ No newline at end of file diff --git a/samples/word/replace_the_header/vb/Program.vb b/samples/word/replace_the_header/vb/Program.vb index 33536bde..6e81b058 100644 --- a/samples/word/replace_the_header/vb/Program.vb +++ b/samples/word/replace_the_header/vb/Program.vb @@ -1,8 +1,15 @@ +' Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Wordprocessing Module Program Sub Main(args As String()) + ' + Dim fromFile As String = args(0) + Dim toFile As String = args(1) + + AddHeaderFromTo(fromFile, toFile) + ' End Sub @@ -43,4 +50,5 @@ Module Program Next End Using End Sub -End Module \ No newline at end of file +End Module +' diff --git a/samples/word/replace_the_styles_parts/cs/Program.cs b/samples/word/replace_the_styles_parts/cs/Program.cs index 2c94bb90..fbbddfb7 100644 --- a/samples/word/replace_the_styles_parts/cs/Program.cs +++ b/samples/word/replace_the_styles_parts/cs/Program.cs @@ -1,38 +1,57 @@ +// using DocumentFormat.OpenXml.Packaging; using System; using System.IO; using System.Xml; using System.Xml.Linq; -ReplaceStyles(args[0], args[1]); // Replace the styles in the "to" document with the styles in // the "from" document. +// static void ReplaceStyles(string fromDoc, string toDoc) +// { + + // // Extract and replace the styles part. var node = ExtractStylesPart(fromDoc, false); + if (node is not null) + { ReplaceStylesPart(toDoc, node, false); + } + // + // // Extract and replace the stylesWithEffects part. To fully support // round-tripping from Word 2010 to Word 2007, you should // replace this part, as well. node = ExtractStylesPart(fromDoc); + if (node is not null) + { ReplaceStylesPart(toDoc, node); + } + return; + // } // Given a file and an XDocument instance that contains the content of // a styles or stylesWithEffects part, replace the styles in the file // with the styles in the XDocument. + +// static void ReplaceStylesPart(string fileName, XDocument newStyles, bool setStylesWithEffectsPart = true) +// { + + // // Open the document for write access and get a reference. using (var document = WordprocessingDocument.Open(fileName, true)) { - if (document.MainDocumentPart is null || document.MainDocumentPart.StyleDefinitionsPart is null || document.MainDocumentPart.StylesWithEffectsPart is null) + if (document.MainDocumentPart is null || (document.MainDocumentPart.StyleDefinitionsPart is null && document.MainDocumentPart.StylesWithEffectsPart is null)) { throw new ArgumentNullException("MainDocumentPart and/or one or both of the Styles parts is null."); } @@ -42,18 +61,28 @@ static void ReplaceStylesPart(string fileName, XDocument newStyles, bool setStyl // Assign a reference to the appropriate part to the // stylesPart variable. + StylesPart? stylesPart = null; + // + + // if (setStylesWithEffectsPart) + { stylesPart = docPart.StylesWithEffectsPart; + } else + { stylesPart = docPart.StyleDefinitionsPart; + } + // + // // If the part exists, populate it with the new styles. if (stylesPart is not null) { - newStyles.Save(new StreamWriter(stylesPart.GetStream( - FileMode.Create, FileAccess.Write))); + newStyles.Save(new StreamWriter(stylesPart.GetStream(FileMode.Create, FileAccess.Write))); } + // } } @@ -70,21 +99,29 @@ static XDocument ExtractStylesPart(string fileName, bool getStylesWithEffectsPar // Get a reference to the main document part. var docPart = document.MainDocumentPart; - if (docPart is null || docPart.StyleDefinitionsPart is null || docPart.StylesWithEffectsPart is null) + if (docPart is null) { - throw new ArgumentNullException("MainDocumentPart and/or one or both of the Styles parts is null."); + throw new ArgumentNullException("MainDocumentPart is null."); } // Assign a reference to the appropriate part to the // stylesPart variable. - StylesPart? stylesPart = null; - if (getStylesWithEffectsPart) + StylesPart stylesPart; + + if (getStylesWithEffectsPart && docPart.StylesWithEffectsPart is not null) + { stylesPart = docPart.StylesWithEffectsPart; - else + } + else if (docPart.StyleDefinitionsPart is not null) + { stylesPart = docPart.StyleDefinitionsPart; + } + else + { + throw new ArgumentNullException("StyleWithEffectsPart and StyleDefinitionsPart are undefined"); + } - using (var reader = XmlNodeReader.Create( - stylesPart.GetStream(FileMode.Open, FileAccess.Read))) + using (var reader = XmlNodeReader.Create(stylesPart.GetStream(FileMode.Open, FileAccess.Read))) { // Create the XDocument. styles = XDocument.Load(reader); @@ -92,4 +129,12 @@ static XDocument ExtractStylesPart(string fileName, bool getStylesWithEffectsPar } // Return the XDocument instance. return styles; -} \ No newline at end of file +} +// + +// +string fromDoc = args[0]; +string toDoc = args[1]; + +ReplaceStyles(fromDoc, toDoc); +// diff --git a/samples/word/replace_the_styles_parts/vb/Program.vb b/samples/word/replace_the_styles_parts/vb/Program.vb index 602f3802..e14c0b71 100644 --- a/samples/word/replace_the_styles_parts/vb/Program.vb +++ b/samples/word/replace_the_styles_parts/vb/Program.vb @@ -1,58 +1,88 @@ +' Imports System.IO Imports System.Xml Imports DocumentFormat.OpenXml.Packaging Module Program Sub Main(args As String()) + ' + Dim fromDoc As String = args(0) + Dim toDoc As String = args(1) + + ReplaceStyles(fromDoc, toDoc) + ' End Sub ' Replace the styles in the "to" document with the styles ' in the "from" document. + + ' Public Sub ReplaceStyles(fromDoc As String, toDoc As String) + ' + + ' ' Extract and copy the styles part. Dim node = ExtractStylesPart(fromDoc, False) + If node IsNot Nothing Then ReplaceStylesPart(toDoc, node, False) End If + ' + ' ' Extract and copy the stylesWithEffects part. To fully support ' round-tripping from Word 2013+ to Word 2010, you should ' replace this part, as well. node = ExtractStylesPart(fromDoc, True) + If node IsNot Nothing Then ReplaceStylesPart(toDoc, node, True) End If + + Return + ' End Sub ' Given a file and an XDocument instance that contains the content of ' a styles or stylesWithEffects part, replace the styles in the file ' with the styles in the XDocument. - Public Sub ReplaceStylesPart( - ByVal fileName As String, ByVal newStyles As XDocument, - Optional ByVal setStylesWithEffectsPart As Boolean = True) + ' + Public Sub ReplaceStylesPart(ByVal fileName As String, ByVal newStyles As XDocument, Optional ByVal setStylesWithEffectsPart As Boolean = True) + ' + + ' ' Open the document for write access and get a reference. Using document = WordprocessingDocument.Open(fileName, True) + If document.MainDocumentPart Is Nothing Or (document.MainDocumentPart.StyleDefinitionsPart Is Nothing And document.MainDocumentPart.StylesWithEffectsPart Is Nothing) Then + Throw New ArgumentNullException("MainDocumentPart and/or one or both of the Styles parts is nothing.") + End If + ' Get a reference to the main document part. Dim docPart = document.MainDocumentPart ' Assign a reference to the appropriate part to the ' stylesPart variable. Dim stylesPart As StylesPart = Nothing + ' + + ' If setStylesWithEffectsPart Then stylesPart = docPart.StylesWithEffectsPart Else stylesPart = docPart.StyleDefinitionsPart End If + ' + ' ' If the part exists, populate it with the new styles. If stylesPart IsNot Nothing Then - newStyles.Save(New StreamWriter( - stylesPart.GetStream(FileMode.Create, FileAccess.Write))) + newStyles.Save(New StreamWriter(stylesPart.GetStream(FileMode.Create, FileAccess.Write))) End If + ' End Using End Sub @@ -71,25 +101,29 @@ Module Program ' Get a reference to the main document part. Dim docPart = document.MainDocumentPart + If docPart Is Nothing Then + Throw New ArgumentException("MainDocumentPart is Nothing") + End If + ' Assign a reference to the appropriate part to the ' stylesPart variable. Dim stylesPart As StylesPart = Nothing - If getStylesWithEffectsPart Then + + If getStylesWithEffectsPart And docPart.StylesWithEffectsPart IsNot Nothing Then stylesPart = docPart.StylesWithEffectsPart - Else + ElseIf docPart.StyleDefinitionsPart IsNot Nothing Then stylesPart = docPart.StyleDefinitionsPart + Else + Throw New ArgumentException("StyleWithEffectsPart and StyleDefinitionsPart are Nothing") End If - ' If the part exists, read it into the XDocument. - If stylesPart IsNot Nothing Then - Using reader = XmlNodeReader.Create( - stylesPart.GetStream(FileMode.Open, FileAccess.Read)) - ' Create the XDocument: - styles = XDocument.Load(reader) - End Using - End If + Using reader = XmlNodeReader.Create(stylesPart.GetStream(FileMode.Open, FileAccess.Read)) + ' Create the XDocument: + styles = XDocument.Load(reader) + End Using End Using ' Return the XDocument instance. Return styles End Function -End Module \ No newline at end of file +End Module +' diff --git a/samples/word/retrieve_application_property_values/cs/Program.cs b/samples/word/retrieve_application_property_values/cs/Program.cs index 20fd8b8d..567b5747 100644 --- a/samples/word/retrieve_application_property_values/cs/Program.cs +++ b/samples/word/retrieve_application_property_values/cs/Program.cs @@ -1,19 +1,23 @@ +// using DocumentFormat.OpenXml.Packaging; using System; - -GetApplicationProperty(args[0]); - static void GetApplicationProperty(string fileName) { + // using (WordprocessingDocument document = WordprocessingDocument.Open(fileName, false)) { + // + + // if (document.ExtendedFilePropertiesPart is null) { throw new ArgumentNullException("ExtendedFilePropertiesPart is null."); } var props = document.ExtendedFilePropertiesPart.Properties; + // + // if (props.Company is not null) Console.WriteLine("Company = " + props.Company.Text); @@ -22,5 +26,9 @@ static void GetApplicationProperty(string fileName) if (props.Manager is not null) Console.WriteLine("Manager = " + props.Manager.Text); + // } } +// + +GetApplicationProperty(args[0]); diff --git a/samples/word/retrieve_application_property_values/vb/Program.vb b/samples/word/retrieve_application_property_values/vb/Program.vb index 5b240015..1e009351 100644 --- a/samples/word/retrieve_application_property_values/vb/Program.vb +++ b/samples/word/retrieve_application_property_values/vb/Program.vb @@ -1,15 +1,27 @@ +' +Imports System.Runtime.Serialization Imports DocumentFormat.OpenXml.Packaging Module Module1 - Private Const FILENAME As String = - "C:\Users\Public\Documents\DocumentProperties.docx" + Sub Main(args As String()) + GetPropertyValues(args(0)) + End Sub + + Public Sub GetPropertyValues(ByVal fileName As String) + ' + Using document As WordprocessingDocument = WordprocessingDocument.Open(fileName, False) + ' - Sub Main() - Using document As WordprocessingDocument = - WordprocessingDocument.Open(FILENAME, False) + ' + If document.ExtendedFilePropertiesPart Is Nothing Then + Throw New ArgumentNullException("ExtendedFileProperties is Nothing") + End If Dim props = document.ExtendedFilePropertiesPart.Properties + ' + + ' If props.Company IsNot Nothing Then Console.WriteLine("Company = " & props.Company.Text) End If @@ -21,6 +33,8 @@ Module Module1 If props.Manager IsNot Nothing Then Console.WriteLine("Manager = " & props.Manager.Text) End If + ' End Using End Sub -End Module \ No newline at end of file +End Module +' diff --git a/samples/word/retrieve_comments/cs/Program.cs b/samples/word/retrieve_comments/cs/Program.cs index 03406339..2c796be7 100644 --- a/samples/word/retrieve_comments/cs/Program.cs +++ b/samples/word/retrieve_comments/cs/Program.cs @@ -1,18 +1,20 @@ +// using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System; -GetCommentsFromDocument(args[0]); - static void GetCommentsFromDocument(string fileName) { + // using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(fileName, false)) { if (wordDoc.MainDocumentPart is null || wordDoc.MainDocumentPart.WordprocessingCommentsPart is null) { throw new System.ArgumentNullException("MainDocumentPart and/or WordprocessingCommentsPart is null."); } + // + // WordprocessingCommentsPart commentsPart = wordDoc.MainDocumentPart.WordprocessingCommentsPart; if (commentsPart is not null && commentsPart.Comments is not null) @@ -22,5 +24,9 @@ static void GetCommentsFromDocument(string fileName) Console.WriteLine(comment.InnerText); } } + // } -} \ No newline at end of file +} +// + +GetCommentsFromDocument(args[0]); diff --git a/samples/word/retrieve_comments/vb/Program.vb b/samples/word/retrieve_comments/vb/Program.vb index 81f28a22..d8de0aa2 100644 --- a/samples/word/retrieve_comments/vb/Program.vb +++ b/samples/word/retrieve_comments/vb/Program.vb @@ -1,26 +1,34 @@ +' Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Wordprocessing Module Program Sub Main(args As String()) + GetCommentsFromDocument(args(0)) End Sub + Public Sub GetCommentsFromDocument(ByVal fileName As String) + ' + Using wordDoc As WordprocessingDocument = WordprocessingDocument.Open(fileName, False) - Public Sub GetCommentsFromDocument(ByVal fileName As String) - Using wordDoc As WordprocessingDocument = - WordprocessingDocument.Open(fileName, False) + If wordDoc.MainDocumentPart Is Nothing Or wordDoc.MainDocumentPart.WordprocessingCommentsPart Is Nothing Then + Throw New ArgumentNullException("MainDocumentPart and/or WordprocessingCommentsPart is null.") + End If + ' - Dim commentsPart As WordprocessingCommentsPart = - wordDoc.MainDocumentPart.WordprocessingCommentsPart + ' + Dim commentsPart As WordprocessingCommentsPart = wordDoc.MainDocumentPart.WordprocessingCommentsPart - If commentsPart IsNot Nothing AndAlso - commentsPart.Comments IsNot Nothing Then + If commentsPart IsNot Nothing AndAlso commentsPart.Comments IsNot Nothing Then For Each comment As Comment In commentsPart.Comments.Elements(Of Comment)() Console.WriteLine(comment.InnerText) Next End If + ' + End Using End Sub -End Module \ No newline at end of file +End Module +' diff --git a/samples/word/set_a_custom_property/cs/Program.cs b/samples/word/set_a_custom_property/cs/Program.cs index cb36f3d3..b3f17ea3 100644 --- a/samples/word/set_a_custom_property/cs/Program.cs +++ b/samples/word/set_a_custom_property/cs/Program.cs @@ -1,3 +1,4 @@ +// using DocumentFormat.OpenXml.CustomProperties; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.VariantTypes; @@ -5,16 +6,20 @@ using System.IO; using System.Linq; +// static string SetCustomProperty( string fileName, string propertyName, object propertyValue, PropertyTypes propertyType) + // { // Given a document name, a property name/value, and the property type, // add a custom property to a document. The method returns the original // value, if it existed. + + // string? returnValue = string.Empty; var newProp = new CustomDocumentProperty(); @@ -83,15 +88,22 @@ static string SetCustomProperty( // property to a valid value, throw an exception. throw new InvalidDataException("propertyValue"); } + // + // // Now that you have handled the parameters, start // working on the document. newProp.FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"; newProp.Name = propertyName; + // + // using (var document = WordprocessingDocument.Open(fileName, true)) { var customProps = document.CustomFilePropertiesPart; + // + + // if (customProps is null) { // No custom properties? Add the part, and the @@ -99,13 +111,20 @@ static string SetCustomProperty( customProps = document.AddCustomFilePropertiesPart(); customProps.Properties = new Properties(); } + // + // var props = customProps.Properties; + if (props is not null) { + // + // This will trigger an exception if the property's Name // property is null, but if that happens, the property is damaged, // and probably should raise an exception. + + // var prop = props.FirstOrDefault(p => ((CustomDocumentProperty)p).Name!.Value == propertyName); // Does the property exist? If so, get the return value, @@ -115,11 +134,9 @@ static string SetCustomProperty( returnValue = prop.InnerText; prop.Remove(); } - else - { - throw new System.ArgumentException("propertyName property was not found or damaged."); - } + // + // // Append the new property, and // fix up all the property ID values. // The PropertyId value must start at 2. @@ -130,11 +147,27 @@ static string SetCustomProperty( item.PropertyId = pid++; } props.Save(); + // } } + + // return returnValue; + // } +// + +// +string fileName = args[0]; + +Console.WriteLine(string.Join("Manager = ", SetCustomProperty(fileName, "Manager", "Pedro", PropertyTypes.Text))); + +Console.WriteLine(string.Join("Manager = ", SetCustomProperty(fileName, "Manager", "Shweta", PropertyTypes.Text))); +Console.WriteLine(string.Join("ReviewDate = ", SetCustomProperty(fileName, "ReviewDate", DateTime.Parse("01/26/2024"), PropertyTypes.DateTime))); +// + +// enum PropertyTypes : int { YesNo, @@ -142,4 +175,6 @@ enum PropertyTypes : int DateTime, NumberInteger, NumberDouble -} \ No newline at end of file +} +// + diff --git a/samples/word/set_a_custom_property/vb/Program.vb b/samples/word/set_a_custom_property/vb/Program.vb index 2fb9d8f8..4717d9d3 100644 --- a/samples/word/set_a_custom_property/vb/Program.vb +++ b/samples/word/set_a_custom_property/vb/Program.vb @@ -5,10 +5,18 @@ Imports DocumentFormat.OpenXml.VariantTypes Module Program Sub Main(args As String()) - End Sub + ' + Dim fileName As String = args(0) + + Console.WriteLine(String.Join("Manager = ", SetCustomProperty(fileName, "Manager", "George", PropertyTypes.Text))) + Console.WriteLine(String.Join("Manager = ", SetCustomProperty(fileName, "Manager", "Olga", PropertyTypes.Text))) + Console.WriteLine(String.Join("ReviewDate = ", SetCustomProperty(fileName, "ReviewDate", #01/26/2024#, PropertyTypes.DateTime))) + ' + End Sub + ' Public Enum PropertyTypes YesNo Text @@ -16,17 +24,21 @@ Module Program NumberInteger NumberDouble End Enum + ' + ' Public Function SetCustomProperty( ByVal fileName As String, ByVal propertyName As String, ByVal propertyValue As Object, ByVal propertyType As PropertyTypes) As String + ' ' Given a document name, a property name/value, and the property type, ' add a custom property to a document. The method returns the original ' value, if it existed. + ' Dim returnValue As String = Nothing Dim newProp As New CustomDocumentProperty @@ -77,36 +89,52 @@ Module Program ' property to a valid value, throw an exception. Throw New InvalidDataException("propertyValue") End If + ' + ' ' Now that you have handled the parameters, start ' working on the document. newProp.FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" newProp.Name = propertyName + ' + ' Using document = WordprocessingDocument.Open(fileName, True) Dim customProps = document.CustomFilePropertiesPart + ' + + ' If customProps Is Nothing Then ' No custom properties? Add the part, and the ' collection of properties now. customProps = document.AddCustomFilePropertiesPart customProps.Properties = New Properties End If + ' + ' Dim props = customProps.Properties + If props IsNot Nothing Then + ' + ' This will trigger an exception is the property's Name property ' is null, but if that happens, the property is damaged, and ' probably should raise an exception. - Dim prop = props. - Where(Function(p) CType(p, CustomDocumentProperty). - Name.Value = propertyName).FirstOrDefault() + + ' + Dim prop = props.Where(Function(p) CType(p, CustomDocumentProperty).Name.Value = propertyName).FirstOrDefault() + ' Does the property exist? If so, get the return value, ' and then delete the property. + If prop IsNot Nothing Then returnValue = prop.InnerText prop.Remove() End If + ' + ' ' Append the new property, and ' fix up all the property ID values. ' The PropertyId value must start at 2. @@ -117,10 +145,14 @@ Module Program pid += 1 Next props.Save() + ' + End If End Using + ' Return returnValue + ' End Function End Module \ No newline at end of file From a1b162cc0379e8c9a57ba85ea7eb15a7a1c91736 Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Tue, 6 Feb 2024 15:24:33 -0800 Subject: [PATCH 006/103] closes #219 --- ...rocessing-document-for-read-only-access.md | 167 ++++++------------ .../open_for_read_only_access/cs/Program.cs | 95 +++++++++- .../open_for_read_only_access/vb/Program.vb | 66 ++++++- 3 files changed, 205 insertions(+), 123 deletions(-) diff --git a/docs/word/how-to-open-a-word-processing-document-for-read-only-access.md b/docs/word/how-to-open-a-word-processing-document-for-read-only-access.md index 79bdaf9f..b3d0baed 100644 --- a/docs/word/how-to-open-a-word-processing-document-for-read-only-access.md +++ b/docs/word/how-to-open-a-word-processing-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: 02/06/2024 ms.localizationpriority: high --- # Open a word processing document for read-only access @@ -24,6 +24,7 @@ access. --------------------------------------------------------------------------------- ## 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 so in a way that ensures the document remains unchanged. In these instances, you want to open the document for @@ -32,7 +33,8 @@ programmatically open a read-only word processing document. -------------------------------------------------------------------------------- -## Create a WordprocessingDocument Object +## Create a WordprocessingDocument Object + In the Open XML SDK, the class represents a Word document package. To work with a Word document, first create an instance of the @@ -45,106 +47,74 @@ document. The package can also contain additional parts. Notice that in a Word document, the text in the main document part is represented in the package as XML using WordprocessingML markup. -To create the class instance from the document you call one of the **Open** methods. Several **Open** methods are provided, each with a different +To create the class instance from the document you call one of the `Open` 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 Method|Class Library Reference Topic|Description --|--|-- -Open(String, Boolean)|[Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) |Create an instance of the class from the specified file. -Open(Stream, Boolean)|[Open(Stream, Boolean)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) |Create an instance of the class from the specified IO stream. -Open(String, Boolean, OpenSettings)|[Open(String, Boolean, OpenSettings)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) |Create an instance of the class from the specified file. -Open(Stream, Boolean, OpenSettings)|[Open(Stream, Boolean, OpenSettings)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) |Create an instance of the class from the specified I/O stream. +Open(String, Boolean)| |Create an instance of the class from the specified file. +Open(Stream, Boolean)| |Create an instance of the class from the specified IO stream. +Open(String, Boolean, OpenSettings)| |Create an instance of the class from the specified file. +Open(Stream, Boolean, OpenSettings)| |Create an instance of the class from the specified I/O stream. -The table above lists only those **Open** +The table above 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, you 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 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 the table above; with a signature +sample code uses this technique. It uses the first `Open` method in the table above; with a signature that requires two parameters. The first parameter takes a string that represents the full path filename from which you want to open the -document. The second parameter is either **true** or **false**; this -example uses **false** and indicates whether +document. The second parameter is either `true` or `false`; this +example uses `false` and indicates whether you want to open the file for editing. -The following code example calls the **Open** +The following code example calls the `Open` Method. ### [C#](#tab/cs-0) -```csharp - // Open a WordprocessingDocument for read-only access based on a filepath. - using (WordprocessingDocument wordDocument = - WordprocessingDocument.Open(filepath, false)) -``` - +[!code-csharp[](../../samples/word/open_for_read_only_access/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - ' Open a WordprocessingDocument for read-only access based on a filepath. - Using wordDocument As WordprocessingDocument = WordprocessingDocument.Open(filepath, False) -``` +[!code-vb[](../../samples/word/open_for_read_only_access/vb/Program.vb#snippet1)] *** -The other two **Open** methods create an +The other two `Open` methods create an instance of the class based on an input/output stream. You might employ this approach, -for instance, if you have a Microsoft SharePoint Foundation 2010 +for instance, if you have a Microsoft SharePoint Online application that uses stream input/output, and you want to use the Open XML SDK to work with a document. The following code example opens a document based on a stream. ### [C#](#tab/cs-1) -```csharp - Stream stream = File.Open(strDoc, FileMode.Open); - // Open a WordprocessingDocument for read-only access based on a stream. - using (WordprocessingDocument wordDocument = - WordprocessingDocument.Open(stream, false)) -``` - +[!code-csharp[](../../samples/word/open_for_read_only_access/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-1) -```vb - Dim stream As Stream = File.Open(strDoc, FileMode.Open) - ' Open a WordprocessingDocument for read-only access based on a stream. - Using wordDocument As WordprocessingDocument = WordprocessingDocument.Open(stream, False) -``` +[!code-vb[](../../samples/word/open_for_read_only_access/vb/Program.vb#snippet3)] *** Suppose you have an application that employs 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 read only. -While the Open XML SDK includes method overloads that 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. +While the Open XML SDK includes method overloads that accept a +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 read-only to begin with +The recommended method is to open the package as read-only to begin with prior to creating the instance of the class, as shown in the second example in the sample code. The following code example performs this operation. ### [C#](#tab/cs-2) -```csharp - // Open System.IO.Packaging.Package. - Package wordPackage = Package.Open(filepath, FileMode.Open, FileAccess.Read); - - // Open a WordprocessingDocument based on a package. - using (WordprocessingDocument wordDocument = - WordprocessingDocument.Open(wordPackage)) -``` - +[!code-csharp[](../../samples/word/open_for_read_only_access/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-2) -```vb - ' Open System.IO.Packaging.Package. - Dim wordPackage As Package = Package.Open(filepath, FileMode.Open, FileAccess.Read) - - ' Open a WordprocessingDocument based on a package. - Using wordDocument As WordprocessingDocument = WordprocessingDocument.Open(wordPackage) -``` +[!code-vb[](../../samples/word/open_for_read_only_access/vb/Program.vb#snippet2)] *** @@ -154,16 +124,9 @@ a reference to the existing document body, as shown in the following code example. ### [C#](#tab/cs-3) -```csharp - // Assign a reference to the existing document body. - Body body = wordprocessingDocument.MainDocumentPart.Document.Body; -``` - +[!code-csharp[](../../samples/word/open_for_read_only_access/cs/Program.cs#snippet4)] ### [Visual Basic](#tab/vb-3) -```vb - ' Assign a reference to the existing document body. - Dim body As Body = wordprocessingDocument.MainDocumentPart.Document.Body -``` +[!code-vb[](../../samples/word/open_for_read_only_access/vb/Program.vb#snippet4)] *** @@ -176,71 +139,55 @@ code example. The sample code shows how you can add some text and attempt to save the changes to show that access is read-only. Once you have access to the body of the main document part, you add text by adding instances of the -**Paragraph**, **Run**, and **Text** +, +, and classes. This generates the required WordprocessingML markup. The following code example adds the paragraph, run, and text. ### [C#](#tab/cs-4) -```csharp - // Attempt to add some text. - Paragraph para = body.AppendChild(new Paragraph()); - Run run = para.AppendChild(new Run()); - run.AppendChild(new Text("Append text in body, but text is not saved - OpenWordprocessingDocumentReadonly")); - - // Call Save to generate an exception and show that access is read-only. - wordDocument.MainDocumentPart.Document.Save(); -``` - +[!code-csharp[](../../samples/word/open_for_read_only_access/cs/Program.cs#snippet5)] ### [Visual Basic](#tab/vb-4) -```vb - ' Attempt to add some text. - Dim para As Paragraph = body.AppendChild(New Paragraph()) - Dim run As Run = para.AppendChild(New Run()) - run.AppendChild(New Text("Append text in body, but text is not saved - OpenWordprocessingDocumentReadonly")) - - ' Call Save to generate an exception and show that access is read-only. - wordDocument.MainDocumentPart.Document.Save() -``` +[!code-vb[](../../samples/word/open_for_read_only_access/vb/Program.vb#snippet5)] *** -------------------------------------------------------------------------------- ## Sample Code -The first example method shown here, **OpenWordprocessingDocumentReadOnly**, opens a Word +The first example method shown here, `OpenWordprocessingDocumentReadOnly`, opens a Word document for read-only access. Call it by passing a full path to the file that you want to open. For example, the following code example -opens the Word12.docx file in the Public Documents folder for read-only -access. +opens the file path from the first command line argument for read-only access. ### [C#](#tab/cs-5) -```csharp - OpenWordprocessingDocumentReadonly(@"c:\Users\Public\Public Documents\Word12.docx"); -``` - +[!code-csharp[](../../samples/word/open_for_read_only_access/cs/Program.cs#snippet6)] ### [Visual Basic](#tab/vb-5) -```vb - OpenWordprocessingDocumentReadonly("c:\Users\Public\Public Documents\Word12.docx") -``` +[!code-vb[](../../samples/word/open_for_read_only_access/vb/Program.vb#snippet6)] *** -The second example method, **OpenWordprocessingPackageReadonly**, shows how to -open a Word document for read-only access from a -System.IO.Packaging.Package. Call it by passing a full path to the file -that you want to open. For example, the following code opens the -Word12.docx file in the Public Documents folder for read-only access. +The second example method, `OpenWordprocessingPackageReadonly`, shows how to +open a Word document for read-only access from a . +Call it by passing a full path to the file +that you want to open. For example, the following code example +opens the file path from the first command line argument for read-only access. ### [C#](#tab/cs-6) -```csharp - OpenWordprocessingPackageReadonly(@"c:\Users\Public\Public Documents\Word12.docx"); -``` - +[!code-csharp[](../../samples/word/open_for_read_only_access/cs/Program.cs#snippet7)] ### [Visual Basic](#tab/vb-6) -```vb - OpenWordprocessingPackageReadonly("c:\Users\Public\Public Documents\Word12.docx") -``` +[!code-vb[](../../samples/word/open_for_read_only_access/vb/Program.vb#snippet7)] *** +The third example method, `OpenWordprocessingStreamReadonly`, shows how to +open a Word document for read-only access from a a stream. +Call it by passing a full path to the file +that you want to open. For example, the following code example +opens the file path from the first command line argument for read-only access. + +### [C#](#tab/cs-6) +[!code-csharp[](../../samples/word/open_for_read_only_access/cs/Program.cs#snippet8)] +### [Visual Basic](#tab/vb-6) +[!code-vb[](../../samples/word/open_for_read_only_access/vb/Program.vb#snippet8)] +*** > [!IMPORTANT] > If you uncomment the statement that saves the file, the program would throw an **IOException** because the file is opened for read-only access. @@ -248,10 +195,10 @@ Word12.docx file in the Public Documents folder for read-only access. The following is the complete sample code in C\# and VB. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/open_for_read_only_access/cs/Program.cs)] +[!code-csharp[](../../samples/word/open_for_read_only_access/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/open_for_read_only_access/vb/Program.vb)] +[!code-vb[](../../samples/word/open_for_read_only_access/vb/Program.vb#snippet0)] -------------------------------------------------------------------------------- ## See also diff --git a/samples/word/open_for_read_only_access/cs/Program.cs b/samples/word/open_for_read_only_access/cs/Program.cs index 43e0ffe4..c9b3bdb3 100644 --- a/samples/word/open_for_read_only_access/cs/Program.cs +++ b/samples/word/open_for_read_only_access/cs/Program.cs @@ -1,32 +1,111 @@ - +// using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System; +using System.IO.Packaging; +using System.IO; -OpenWordprocessingDocumentReadonly(args[0]); static void OpenWordprocessingDocumentReadonly(string filepath) { + // // Open a WordprocessingDocument based on a filepath. - using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(filepath, false)) + using (WordprocessingDocument wordProcessingDocument = WordprocessingDocument.Open(filepath, false)) + // { - if (wordDocument is null) + if (wordProcessingDocument is null) { - throw new ArgumentNullException(nameof(wordDocument)); + throw new ArgumentNullException(nameof(wordProcessingDocument)); } - // Assign a reference to the existing document body. - MainDocumentPart mainDocumentPart = wordDocument.MainDocumentPart ?? wordDocument.AddMainDocumentPart(); + + // + // Assign a reference to the existing document body or create a new one if it is null. + MainDocumentPart mainDocumentPart = wordProcessingDocument.MainDocumentPart ?? wordProcessingDocument.AddMainDocumentPart(); mainDocumentPart.Document ??= new Document(); Body body = mainDocumentPart.Document.Body ?? mainDocumentPart.Document.AppendChild(new Body()); + // + // // Attempt to add some text. Paragraph para = body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); run.AppendChild(new Text("Append text in body, but text is not saved - OpenWordprocessingDocumentReadonly")); // Call Save to generate an exception and show that access is read-only. - //mainDocumentPart.Document.Save(); + // mainDocumentPart.Document.Save(); + // + } +} + +static void OpenWordprocessingPackageReadonly(string filepath) +{ + // + // Open System.IO.Packaging.Package. + Package wordPackage = Package.Open(filepath, FileMode.Open, FileAccess.Read); + + // Open a WordprocessingDocument based on a package. + using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(wordPackage)) + // + { + // Assign a reference to the existing document body or create a new one if it is null. + MainDocumentPart mainDocumentPart = wordDocument.MainDocumentPart ?? wordDocument.AddMainDocumentPart(); + mainDocumentPart.Document ??= new Document(); + + Body body = mainDocumentPart.Document.Body ?? mainDocumentPart.Document.AppendChild(new Body()); + + // Attempt to add some text. + Paragraph para = body.AppendChild(new Paragraph()); + Run run = para.AppendChild(new Run()); + run.AppendChild(new Text("Append text in body, but text is not saved - OpenWordprocessingPackageReadonly")); + + // Call Save to generate an exception and show that access is read-only. + // mainDocumentPart.Document.Save(); + } + + // Close the package. + wordPackage.Close(); +} + + +static void OpenWordprocessingStreamReadonly(string filepath) +{ + // + // Get a stream of the wordprocessing document + using (FileStream fileStream = new FileStream(filepath, FileMode.Open)) + + // Open a WordprocessingDocument for read-only access based on a stream. + using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(fileStream, false)) + // + { + + + // Assign a reference to the existing document body or create a new one if it is null. + MainDocumentPart mainDocumentPart = wordDocument.MainDocumentPart ?? wordDocument.AddMainDocumentPart(); + mainDocumentPart.Document ??= new Document(); + + Body body = mainDocumentPart.Document.Body ?? mainDocumentPart.Document.AppendChild(new Body()); + + // Attempt to add some text. + Paragraph para = body.AppendChild(new Paragraph()); + Run run = para.AppendChild(new Run()); + run.AppendChild(new Text("Append text in body, but text is not saved - OpenWordprocessingStreamReadonly")); + + // Call Save to generate an exception and show that access is read-only. + // mainDocumentPart.Document.Save(); } } +// + +// +OpenWordprocessingDocumentReadonly(args[0]); +// + +// +OpenWordprocessingPackageReadonly(args[0]); +// + +// +OpenWordprocessingStreamReadonly(args[0]); +// diff --git a/samples/word/open_for_read_only_access/vb/Program.vb b/samples/word/open_for_read_only_access/vb/Program.vb index 386fceec..66f8027b 100644 --- a/samples/word/open_for_read_only_access/vb/Program.vb +++ b/samples/word/open_for_read_only_access/vb/Program.vb @@ -1,3 +1,4 @@ +' Imports System.IO Imports System.IO.Packaging Imports DocumentFormat.OpenXml.Packaging @@ -7,30 +8,62 @@ Imports DocumentFormat.OpenXml.Wordprocessing Module MyModule Sub Main(args As String()) + ' + OpenWordprocessingDocumentReadonly(args(0)) + ' + + ' + OpenWordprocessingPackageReadonly(args(0)) + ' + + ' + OpenWordprocessingStreamReadonly(args(0)) + ' End Sub Public Sub OpenWordprocessingDocumentReadonly(ByVal filepath As String) + + ' ' Open a WordprocessingDocument based on a filepath. - Using wordDocument As WordprocessingDocument = WordprocessingDocument.Open(filepath, False) - ' Assign a reference to the existing document body. - Dim body As Body = wordDocument.MainDocumentPart.Document.Body + Using wordProcessingDocument As WordprocessingDocument = WordprocessingDocument.Open(filepath, False) + ' + + ' + ' Assign a reference to the document body. + Dim mainDocumentPart As MainDocumentPart = If(wordProcessingDocument.MainDocumentPart, wordProcessingDocument.AddMainDocumentPart()) + + If wordProcessingDocument.MainDocumentPart.Document Is Nothing Then + wordProcessingDocument.MainDocumentPart.Document = New Document() + End If + + If wordProcessingDocument.MainDocumentPart.Document.Body Is Nothing Then + wordProcessingDocument.MainDocumentPart.Document.Body = New Body() + End If + + Dim body As Body = wordProcessingDocument.MainDocumentPart.Document.Body + ' + ' ' Attempt to add some text. Dim para As Paragraph = body.AppendChild(New Paragraph()) Dim run As Run = para.AppendChild(New Run()) run.AppendChild(New Text("Append text in body, but text is not saved - OpenWordprocessingDocumentReadonly")) ' Call Save to generate an exception and show that access is read-only. - ' wordDocument.MainDocumentPart.Document.Save() + 'wordProcessingDocument.MainDocumentPart.Document.Save() + ' End Using End Sub Public Sub OpenWordprocessingPackageReadonly(ByVal filepath As String) + ' ' Open System.IO.Packaging.Package. Dim wordPackage As Package = Package.Open(filepath, FileMode.Open, FileAccess.Read) ' Open a WordprocessingDocument based on a package. Using wordDocument As WordprocessingDocument = WordprocessingDocument.Open(wordPackage) + ' + ' Assign a reference to the existing document body. Dim body As Body = wordDocument.MainDocumentPart.Document.Body @@ -46,4 +79,27 @@ Module MyModule ' Close the package. wordPackage.Close() End Sub -End Module \ No newline at end of file + + Public Sub OpenWordprocessingStreamReadonly(ByVal filepath As String) + ' + ' Get a stream of the wordprocessing document + Using fileStream As FileStream = New FileStream(filepath, FileMode.Open) + ' Open a WordprocessingDocument for read-only access based on a stream. + Using wordDocument As WordprocessingDocument = WordprocessingDocument.Open(fileStream, False) + ' + + ' Assign a reference to the existing document body. + Dim body As Body = wordDocument.MainDocumentPart.Document.Body + + ' Attempt to add some text. + Dim para As Paragraph = body.AppendChild(New Paragraph()) + Dim run As Run = para.AppendChild(New Run()) + run.AppendChild(New Text("Append text in body, but text is not saved - OpenWordprocessingStreamReadonly")) + + ' Call Save to generate an exception and show that access is read-only. + ' wordDocument.MainDocumentPart.Document.Save() + End Using + End Using + End Sub +End Module +' From 3368d85529169786932680d08e92e44747d7160c Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Wed, 7 Feb 2024 15:45:14 -0800 Subject: [PATCH 007/103] closes #218 --- ...a-table-into-a-word-processing-document.md | 243 +++++------------- samples/word/insert_a_table/cs/Program.cs | 24 +- samples/word/insert_a_table/vb/Program.vb | 54 +++- 3 files changed, 132 insertions(+), 189 deletions(-) diff --git a/docs/word/how-to-insert-a-table-into-a-word-processing-document.md b/docs/word/how-to-insert-a-table-into-a-word-processing-document.md index e145ca17..1adda8a1 100644 --- a/docs/word/how-to-insert-a-table-into-a-word-processing-document.md +++ b/docs/word/how-to-insert-a-table-into-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: 02/07/2024 ms.localizationpriority: high --- # Insert a table into a word processing document @@ -25,56 +25,45 @@ document. ## Getting a WordprocessingDocument Object To open an existing document, instantiate the class as shown in the -following **using** statement. In the same +following `using` statement. In the same statement, open the word processing file at the specified filepath by -using the **Open** method, with the Boolean -parameter set to **true** in order to enable +using the method, with the Boolean +parameter set to `true` in order to enable editing the document. ### [C#](#tab/cs-0) -```csharp - using (WordprocessingDocument doc = - WordprocessingDocument.Open(filepath, true)) - { - // Insert other code here. - } -``` - +[!code-csharp[](../../samples/word/insert_a_table/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - Using doc As WordprocessingDocument = WordprocessingDocument.Open(filepath, True) - ' Insert other code here. - End Using -``` +[!code-vb[](../../samples/word/insert_a_table/vb/Program.vb#snippet1)] *** -The **using** statement provides a recommended +The `using` statement provides a recommended alternative to the typical .Create, .Save, .Close sequence. It ensures -that the **Dispose** method (internal method +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, in this case doc. 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**. +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 and + as long as you use `using`. ## Structure of a Table -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** +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 document might contain a table as in this example. A table is a set of paragraphs (and other block-level -content) arranged in rows and columns. Tables in **WordprocessingML** are defined via the **tbl** element, which is analogous to the HTML table +content) arranged in rows and columns. Tables in `WordprocessingML` +are defined via the `tbl` element, which is analogous to the HTML table tag. Consider an empty one-cell table (i.e. a table with one row, one column) and 1 point borders on all sides. This table is represented by -the following **WordprocessingML** markup +the following `WordprocessingML` markup segment. ```xml @@ -83,7 +72,7 @@ segment. - + @@ -103,159 +92,67 @@ segment. ``` This table specifies table-wide properties of 100% of page width using -the **tblW** element, a set of table borders -using the **tblBorders** element, the table +the `tblW` element, a set of table borders +using the `tblBorders` element, the table grid, which defines a set of shared vertical edges within the table -using the **tblGrid** element, and a single -table row using the **tr** element. +using the `tblGrid` element, and a single +table row using the `tr` element. ## How the Sample Code Works -In sample code, after you open the document in the **using** statement, you create a new [Table](/dotnet/api/documentformat.openxml.wordprocessing.table) object. Then you create a [TableProperties](/dotnet/api/documentformat.openxml.wordprocessing.tableproperties) object and specify its -border information. The **TableProperties** -class contains an overloaded constructor [TableProperties()](/dotnet/api/documentformat.openxml.wordprocessing.tableproperties.-ctor) that takes a **params** array of type [OpenXmlElement](/dotnet/api/documentformat.openxml.openxmlelement). The code uses this -constructor to instantiate a **TableProperties** object with [BorderType](/dotnet/api/documentformat.openxml.wordprocessing.bordertype) objects for each border, -instantiating each **BorderType** and -specifying its value using object initializers. After it has been -instantiated, append the **TableProperties** -object to the table. +In sample code, after you open the document in the `using` statement, you create a new + object. Then you create +a object and specify its border information. +The class contains an overloaded +constructor +that takes a `params` array of type . The code uses this +constructor to instantiate a `TableProperties` object with +objects for each border, instantiating each `BorderType` and specifying its value using object initializers. +After it has been instantiated, append the `TableProperties` object to the table. ### [C#](#tab/cs-1) -```csharp - // Create an empty table. - Table table = new Table(); - - // Create a TableProperties object and specify its border information. - TableProperties tblProp = new TableProperties( - new TableBorders( - new TopBorder() { Val = new EnumValue(BorderValues.Dashed), Size = 24 }, - new BottomBorder() { Val = new EnumValue(BorderValues.Dashed), Size = 24 }, - new LeftBorder() { Val = new EnumValue(BorderValues.Dashed), Size = 24 }, - new RightBorder() { Val = new EnumValue(BorderValues.Dashed), Size = 24 }, - new InsideHorizontalBorder() { Val = new EnumValue(BorderValues.Dashed), Size = 24 }, - new InsideVerticalBorder() { Val = new EnumValue(BorderValues.Dashed), Size = 24 } - ) - ); - // Append the TableProperties object to the empty table. - table.AppendChild(tblProp); -``` - +[!code-csharp[](../../samples/word/insert_a_table/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-1) -```vb - ' Create an empty table. - Dim table As New Table() - - ' Create a TableProperties object and specify its border information. - Dim tblProp As New TableProperties( - New TableBorders( - New TopBorder() With {.Val = New EnumValue(Of BorderValues)(BorderValues.Dashed), .Size = 24}, - New BottomBorder() With {.Val = New EnumValue(Of BorderValues)(BorderValues.Dashed), .Size = 24}, - New LeftBorder() With {.Val = New EnumValue(Of BorderValues)(BorderValues.Dashed), .Size = 24}, - New RightBorder() With {.Val = New EnumValue(Of BorderValues)(BorderValues.Dashed), .Size = 24}, - New InsideHorizontalBorder() With {.Val = New EnumValue(Of BorderValues)(BorderValues.Dashed), .Size = 24}, - New InsideVerticalBorder() With {.Val = New EnumValue(Of BorderValues)(BorderValues.Dashed), .Size = 24})) - - ' Append the TableProperties object to the empty table. - table.AppendChild(Of TableProperties)(tblProp) -``` +[!code-vb[](../../samples/word/insert_a_table/vb/Program.vb#snippet2)] *** The code creates a table row. This section of the code makes extensive -use of the overloaded [Append\[\])](/dotnet/api/documentformat.openxml.openxmlelement.append) methods, which classes derived -from **OpenXmlElement** inherit. The **Append** methods provide a way to either append a -single element or to append a portion of an XML tree, to the end of the -list of child elements under a given parent element. Next, the code -creates a [TableCell](/dotnet/api/documentformat.openxml.wordprocessing.tablecell) object, which represents an -individual table cell, and specifies the width property of the table -cell using a [TableCellProperties](/dotnet/api/documentformat.openxml.wordprocessing.tablecellproperties) object, and the cell -content ("Hello, World!") using a [Text](/dotnet/api/documentformat.openxml.wordprocessing.text) object. In the Open XML Wordprocessing -schema, a paragraph element (**\**) -contains run elements (**\**) which, in -turn, contain text elements (**\**). To -insert text within a table cell using the API, you must create a [Paragraph](/dotnet/api/documentformat.openxml.wordprocessing.paragraph) object that contains a **Run** object that contains a **Text** object that contains the text you want to -insert in the cell. You then append the **Paragraph** object to the **TableCell** object. This creates the proper XML -structure for inserting text into a cell. The **TableCell** is then appended to the [TableRow](/dotnet/api/documentformat.openxml.wordprocessing.tablerow) object. +use of the overloaded methods, +which classes derived from `OpenXmlElement` inherit. The `Append` methods provide +a way to either append a single element or to append a portion of an XML tree, +to the end of the list of child elements under a given parent element. Next, the code +creates a object, which represents +an individual table cell, and specifies the width property of the table cell using a + object, and the cell +content ("Hello, World!") using a object. +In the Open XML Wordprocessing schema, a paragraph element (``) contains run elements (``) +which, in turn, contain text elements (``). To insert text within a table cell using the API, you must create a + object that contains a +object that contains a `Text` object that contains the text you want to insert in the cell. +You then append the `Paragraph` object to the `TableCell` object. This creates the proper XML +structure for inserting text into a cell. The `TableCell` is then appended to the + object. ### [C#](#tab/cs-2) -```csharp - // Create a row. - TableRow tr = new TableRow(); - - // Create a cell. - TableCell tc1 = new TableCell(); - - // Specify the width property of the table cell. - tc1.Append(new TableCellProperties(new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" })); - - // Specify the table cell content. - tc1.Append(new Paragraph(new Run(new Text("Hello, World!")))); - - // Append the table cell to the table row. - tr.Append(tc1); -``` - +[!code-csharp[](../../samples/word/insert_a_table/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-2) -```vb - ' Create a row. - Dim tr As New TableRow() - - ' Create a cell. - Dim tc1 As New TableCell() - - ' Specify the width property of the table cell. - tc1.Append(New TableCellProperties(New TableCellWidth() With {.Type = TableWidthUnitValues.Dxa, .Width = "2400"})) - - ' Specify the table cell content. - tc1.Append(New Paragraph(New Run(New Text("Hello, World!")))) - - ' Append the table cell to the table row. - tr.Append(tc1) -``` +[!code-vb[](../../samples/word/insert_a_table/vb/Program.vb#snippet3)] *** -The code then creates a second table cell. The final section of code -creates another table cell using the overloaded **TableCell** constructor [TableCell(String)](/dotnet/api/documentformat.openxml.wordprocessing.tablecell.-ctor) that takes the [OuterXml](/dotnet/api/documentformat.openxml.openxmlelement.outerxml) property of an existing **TableCell** object as its only argument. After -creating the second table cell, the code appends the **TableCell** to the **TableRow**, appends the **TableRow** to the **Table**, and the **Table** -to the [Document](/dotnet/api/documentformat.openxml.wordprocessing.document) object. +The code then creates a second table cell. The final section of code creates another table cell +using the overloaded `TableCell` constructor +that takes the property of an existing +`TableCell` object as its only argument. After creating the second table cell, the code appends +the `TableCell` to the `TableRow`, appends the `TableRow` to the `Table`, and the `Table` +to the object. ### [C#](#tab/cs-3) -```csharp - // Create a second table cell by copying the OuterXml value of the first table cell. - TableCell tc2 = new TableCell(tc1.OuterXml); - - // Append the table cell to the table row. - tr.Append(tc2); - - // Append the table row to the table. - table.Append(tr); - - // Append the table to the document. - doc.MainDocumentPart.Document.Body.Append(table); - - // Save changes to the MainDocumentPart. - doc.MainDocumentPart.Document.Save(); -``` - +[!code-csharp[](../../samples/word/insert_a_table/cs/Program.cs#snippet4)] ### [Visual Basic](#tab/vb-3) -```vb - ' Create a second table cell by copying the OuterXml value of the first table cell. - Dim tc2 As New TableCell(tc1.OuterXml) - - ' Append the table cell to the table row. - tr.Append(tc2) - - ' Append the table row to the table. - table.Append(tr) - - ' Append the table to the document. - doc.MainDocumentPart.Document.Body.Append(table) - - ' Save changes to the MainDocumentPart. - doc.MainDocumentPart.Document.Save() -``` +[!code-vb[](../../samples/word/insert_a_table/vb/Program.vb#snippet4)] *** @@ -264,33 +161,25 @@ to the [Document](/dotnet/api/documentformat.openxml.wordprocessing.document) ob The following code example shows how to create a table, set its properties, insert text into a cell in the table, copy a cell, and then insert the table into a word processing document. You can invoke the -method **CreateTable** by using the following +method `CreateTable` by using the following call. ### [C#](#tab/cs-4) -```csharp - string fileName = @"C:\Users\Public\Documents\Word10.docx"; - CreateTable(fileName); -``` - +[!code-csharp[](../../samples/word/insert_a_table/cs/Program.cs#snippet5)] ### [Visual Basic](#tab/vb-4) -```vb - Dim fileName As String = "C:\Users\Public\Documents\Word10.docx" - CreateTable(fileName) -``` +[!code-vb[](../../samples/word/insert_a_table/vb/Program.vb#snippet5)] *** -After you run the program inspect the file "Word10.docx" to see the -inserted table. +After you run the program inspect the file to see the inserted table. Following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/insert_a_table/cs/Program.cs)] +[!code-csharp[](../../samples/word/insert_a_table/cs/Program.cs#snippet)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/insert_a_table/vb/Program.vb)] +[!code-vb[](../../samples/word/insert_a_table/vb/Program.vb#snippet)] ## See also diff --git a/samples/word/insert_a_table/cs/Program.cs b/samples/word/insert_a_table/cs/Program.cs index 376d3141..448c53bd 100644 --- a/samples/word/insert_a_table/cs/Program.cs +++ b/samples/word/insert_a_table/cs/Program.cs @@ -1,19 +1,21 @@ +// using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System; -CreateTable(args[0]); // Insert a table into a word processing document. static void CreateTable(string fileName) { // Use the file name and path passed in as an argument - // to open an existing Word 2007 document. + // to open an existing Word document. - using (WordprocessingDocument doc - = WordprocessingDocument.Open(fileName, true)) + // + using (WordprocessingDocument doc = WordprocessingDocument.Open(fileName, true)) + // { + // // Create an empty table. Table table = new Table(); @@ -61,7 +63,9 @@ static void CreateTable(string fileName) // Append the TableProperties object to the empty table. table.AppendChild(tblProp); + // + // // Create a row. TableRow tr = new TableRow(); @@ -77,7 +81,9 @@ static void CreateTable(string fileName) // Append the table cell to the table row. tr.Append(tc1); + // + // // Create a second table cell by copying the OuterXml value of the first table cell. TableCell tc2 = new TableCell(tc1.OuterXml); @@ -94,5 +100,13 @@ static void CreateTable(string fileName) // Append the table to the document. doc.MainDocumentPart.Document.Body.Append(table); + // } -} \ No newline at end of file +} +// + +// +string filePath = args[0]; + +CreateTable(filePath); +// diff --git a/samples/word/insert_a_table/vb/Program.vb b/samples/word/insert_a_table/vb/Program.vb index 51a1195d..52042654 100644 --- a/samples/word/insert_a_table/vb/Program.vb +++ b/samples/word/insert_a_table/vb/Program.vb @@ -1,3 +1,4 @@ +' Imports DocumentFormat.OpenXml Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Wordprocessing @@ -12,6 +13,10 @@ Imports TopBorder = DocumentFormat.OpenXml.Wordprocessing.TopBorder Module MyModule Sub Main(args As String()) + ' + Dim filePath As String = args(0) + CreateTable(filePath) + ' End Sub @@ -20,21 +25,52 @@ Module MyModule ' Use the file name and path passed in as an argument ' to open an existing Word 2007 document. + ' Using doc As WordprocessingDocument = WordprocessingDocument.Open(fileName, True) + ' + + ' ' Create an empty table. Dim table As New Table() ' Create a TableProperties object and specify its border information. Dim tblProp As New TableProperties(New TableBorders( - New TopBorder() With {.Val = New EnumValue(Of BorderValues)(BorderValues.Dashed), .Size = 24}, - New BottomBorder() With {.Val = New EnumValue(Of BorderValues)(BorderValues.Dashed), .Size = 24}, - New LeftBorder() With {.Val = New EnumValue(Of BorderValues)(BorderValues.Dashed), .Size = 24}, - New RightBorder() With {.Val = New EnumValue(Of BorderValues)(BorderValues.Dashed), .Size = 24}, - New InsideHorizontalBorder() With {.Val = New EnumValue(Of BorderValues)(BorderValues.Dashed), .Size = 24}, - New InsideVerticalBorder() With {.Val = New EnumValue(Of BorderValues)(BorderValues.Dashed), .Size = 24})) + New TopBorder() With + { + .Val = New EnumValue(Of BorderValues)(BorderValues.Dashed), + .Size = 24 + }, + New BottomBorder() With + { + .Val = New EnumValue(Of BorderValues)(BorderValues.Dashed), + .Size = 24 + }, + New LeftBorder() With + { + .Val = New EnumValue(Of BorderValues)(BorderValues.Dashed), + .Size = 24 + }, + New RightBorder() With + { + .Val = New EnumValue(Of BorderValues)(BorderValues.Dashed), + .Size = 24 + }, + New InsideHorizontalBorder() With + { + .Val = New EnumValue(Of BorderValues)(BorderValues.Dashed), + .Size = 24 + }, + New InsideVerticalBorder() With + { + .Val = New EnumValue(Of BorderValues)(BorderValues.Dashed), + .Size = 24 + }) + ) ' Append the TableProperties object to the empty table. table.AppendChild(Of TableProperties)(tblProp) + ' + ' ' Create a row. Dim tr As New TableRow() @@ -49,7 +85,9 @@ Module MyModule ' Append the table cell to the table row. tr.Append(tc1) + ' + ' ' Create a second table cell by copying the OuterXml value of the first table cell. Dim tc2 As New TableCell(tc1.OuterXml) @@ -61,6 +99,8 @@ Module MyModule ' Append the table to the document. doc.MainDocumentPart.Document.Body.Append(table) + ' End Using End Sub -End Module \ No newline at end of file +End Module +' From 5f30e911042d0549304f2b37f3e49389c050be98 Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Thu, 8 Feb 2024 11:48:03 -0800 Subject: [PATCH 008/103] closes #310 --- ...to-add-a-new-document-part-to-a-package.md | 3 +- ...ackage-part-to-a-document-part-in-a-dif.md | 11 +---- docs/general/how-to-create-a-package.md | 10 +---- ...tents-of-a-document-part-from-a-package.md | 12 +----- ...o-remove-a-document-part-from-a-package.md | 11 +---- ...heme-part-in-a-word-processing-document.md | 14 +------ ...rch-and-replace-text-in-a-document-part.md | 13 +----- docs/includes/using-statement.md | 11 +++++ .../how-to-apply-a-theme-to-a-presentation.md | 7 +--- ...fill-color-of-a-shape-in-a-presentation.md | 7 +--- ...w-to-delete-a-slide-from-a-presentation.md | 2 +- ...or-from-all-the-slides-in-a-presentatio.md | 7 +--- ...e-external-hyperlinks-in-a-presentation.md | 7 +--- ...l-the-text-in-a-slide-in-a-presentation.md | 7 +--- ...he-text-in-all-slides-in-a-presentation.md | 7 +--- ...les-of-all-the-slides-in-a-presentation.md | 9 +--- ...-insert-a-new-slide-into-a-presentation.md | 9 +--- ...agraph-from-one-presentation-to-another.md | 8 +--- ...ide-to-a-new-position-in-a-presentation.md | 8 +--- ...n-a-table-in-a-word-processing-document.md | 12 +----- ...ssing-document-by-providing-a-file-name.md | 12 +----- ...comment-into-a-word-processing-document.md | 9 +--- ...picture-into-a-word-processing-document.md | 42 ++++--------------- ...a-table-into-a-word-processing-document.md | 13 +----- ...omments-from-a-word-processing-document.md | 6 +-- 25 files changed, 43 insertions(+), 214 deletions(-) create mode 100644 docs/includes/using-statement.md diff --git a/docs/general/how-to-add-a-new-document-part-to-a-package.md b/docs/general/how-to-add-a-new-document-part-to-a-package.md index bc5ba2d2..90d9714d 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 @@ -40,8 +40,7 @@ The code starts with opening a package file by passing a file name to one of the *** -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/using-statement.md)] [!include[Structure](../includes/word/structure.md)] 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..dbfbf88a 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 @@ -57,16 +57,7 @@ order to enable editing the document. ``` *** -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/using-statement.md)] -------------------------------------------------------------------------------- diff --git a/docs/general/how-to-create-a-package.md b/docs/general/how-to-create-a-package.md index c40dea47..a7946d10 100644 --- a/docs/general/how-to-create-a-package.md +++ b/docs/general/how-to-create-a-package.md @@ -59,15 +59,7 @@ template. ``` *** -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/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, 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..1dc5c19a 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 @@ -54,17 +54,7 @@ opened in read-only mode to avoid accidental changes. ``` *** - -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/using-statement.md)] --------------------------------------------------------------------------------- diff --git a/docs/general/how-to-remove-a-document-part-from-a-package.md b/docs/general/how-to-remove-a-document-part-from-a-package.md index fcfacedf..128cd48a 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 @@ -54,16 +54,7 @@ should be opened in read/write mode. *** -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/using-statement.md)] --------------------------------------------------------------------------------- diff --git a/docs/general/how-to-replace-the-theme-part-in-a-word-processing-document.md b/docs/general/how-to-replace-the-theme-part-in-a-word-processing-document.md index a8648b65..5b499b48 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 @@ -49,19 +49,7 @@ to **true** to enable editing the 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 *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/using-statement.md)] ## How to Change Theme in a Word Package 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..9e57abad 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 @@ -53,18 +53,7 @@ to **true** to enable editing the 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 *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/using-statement.md)] -------------------------------------------------------------------------------- diff --git a/docs/includes/using-statement.md b/docs/includes/using-statement.md new file mode 100644 index 00000000..77938662 --- /dev/null +++ b/docs/includes/using-statement.md @@ -0,0 +1,11 @@ +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 and + as long as you use `using`. \ No newline at end of file diff --git a/docs/presentation/how-to-apply-a-theme-to-a-presentation.md b/docs/presentation/how-to-apply-a-theme-to-a-presentation.md index 2182b0ad..4c37d68e 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 @@ -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/using-statement.md)] ----------------------------------------------------------------------------- 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..6939c994 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 @@ -53,12 +53,7 @@ you want to open the 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 *ppt*. +[!include[Using Statement](../includes/using-statement.md)] ## The Structure of the Shape Tree 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..5e679caa 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 @@ -76,7 +76,7 @@ statement. *** -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/using-statement.md)] [!include[Structure](../includes/presentation/structure.md)] 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 index 83f73734..2600ecd0 100644 --- 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 @@ -59,12 +59,7 @@ Options. *** -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/using-statement.md)] [!include[Structure](../includes/presentation/structure.md)] 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..d69df315 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 @@ -58,12 +58,7 @@ path for the file from which you want to open the 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 **document**. +[!include[Using Statement](../includes/using-statement.md)] -------------------------------------------------------------------------------- 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..56c0af4f 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 @@ -56,12 +56,7 @@ 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 **presentationDocument**. +[!include[Using Statement](../includes/using-statement.md)] -------------------------------------------------------------------------------- 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..96ffdbf2 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 @@ -56,12 +56,7 @@ 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 **presentationDocument**. +[!include[Using Statement](../includes/using-statement.md)] -------------------------------------------------------------------------------- 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..44d82d82 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 @@ -55,14 +55,7 @@ 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 -*presentationDocument*. +[!include[Using Statement](../includes/using-statement.md)] [!include[Structure](../includes/presentation/structure.md)] 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..0ed94c26 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 @@ -51,14 +51,7 @@ 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 -*presentationDocument*. +[!include[Using Statement](../includes/using-statement.md)] [!include[Structure](../includes/presentation/structure.md)] 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..6e5103dd 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 @@ -52,13 +52,7 @@ for the file from which you want to open the 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 *doc*. +[!include[Using Statement](../includes/using-statement.md)] [!include[Structure](../includes/presentation/structure.md)] 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..b63644a6 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 @@ -57,13 +57,7 @@ open the 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 **presentationDocument**. +[!include[Using Statement](../includes/using-statement.md)] -------------------------------------------------------------------------------- diff --git a/docs/word/how-to-change-text-in-a-table-in-a-word-processing-document.md b/docs/word/how-to-change-text-in-a-table-in-a-word-processing-document.md index d6232a15..bc951426 100644 --- a/docs/word/how-to-change-text-in-a-table-in-a-word-processing-document.md +++ b/docs/word/how-to-change-text-in-a-table-in-a-word-processing-document.md @@ -42,17 +42,7 @@ To open an existing document, instantiate 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/using-statement.md)] ## The Structure of a Table diff --git a/docs/word/how-to-create-a-word-processing-document-by-providing-a-file-name.md b/docs/word/how-to-create-a-word-processing-document-by-providing-a-file-name.md index 05e0f3ea..b4af6ddd 100644 --- a/docs/word/how-to-create-a-word-processing-document-by-providing-a-file-name.md +++ b/docs/word/how-to-create-a-word-processing-document-by-providing-a-file-name.md @@ -68,17 +68,7 @@ bracketed block, as shown in the following code example. ``` *** - -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 **wordDocument**. 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/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 the method of the class. Having done that, diff --git a/docs/word/how-to-insert-a-comment-into-a-word-processing-document.md b/docs/word/how-to-insert-a-comment-into-a-word-processing-document.md index 02f2c21f..b010c28b 100644 --- a/docs/word/how-to-insert-a-comment-into-a-word-processing-document.md +++ b/docs/word/how-to-insert-a-comment-into-a-word-processing-document.md @@ -48,14 +48,7 @@ editing in the document. ``` *** - -The **using** statement provides a recommended -alternative to the typical .Open, .Save, .Close sequence. It ensures -that the **Dispose** method (internal method -that is 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/using-statement.md)] -------------------------------------------------------------------------------- diff --git a/docs/word/how-to-insert-a-picture-into-a-word-processing-document.md b/docs/word/how-to-insert-a-picture-into-a-word-processing-document.md index 4a17b366..1b291772 100644 --- a/docs/word/how-to-insert-a-picture-into-a-word-processing-document.md +++ b/docs/word/how-to-insert-a-picture-into-a-word-processing-document.md @@ -12,55 +12,31 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 06/28/2021 +ms.date: 02/08/2024 ms.localizationpriority: high --- # Insert a picture into a word processing document This topic shows how to use the classes in the Open XML SDK for Office to programmatically add a picture to a word processing document. - - -------------------------------------------------------------------------------- ## Opening an Existing Document for Editing -To open an existing document, instantiate the class as shown in -the following **using** statement. In the same -statement, open the word processing file at the specified **filepath** by using the [Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) method, with the -Boolean parameter set to **true** in order to +To open an existing document, instantiate the +class as shown in the following `using` statement. In the same +statement, open the word processing file at the specified `filepath`by using the + +method, with the Boolean parameter set to `true` in order to enable editing the document. ### [C#](#tab/cs-0) -```csharp - using (WordprocessingDocument wordprocessingDocument = - WordprocessingDocument.Open(filepath, true)) - { - // Insert other code here. - } -``` - +[!code-csharp[](../../samples/word/insert_a_picture/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - Using wordprocessingDocument As WordprocessingDocument = WordprocessingDocument.Open(filepath, True) - ' Insert other code here. - End Using -``` +[!code-vb[](../../samples/word/insert_a_picture/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 -that is 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 -*wordprocessingDocument*. 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/using-statement.md)] -------------------------------------------------------------------------------- ## The XML Representation of the Graphic Object diff --git a/docs/word/how-to-insert-a-table-into-a-word-processing-document.md b/docs/word/how-to-insert-a-table-into-a-word-processing-document.md index 1adda8a1..ff98004f 100644 --- a/docs/word/how-to-insert-a-table-into-a-word-processing-document.md +++ b/docs/word/how-to-insert-a-table-into-a-word-processing-document.md @@ -37,18 +37,7 @@ editing the document. [!code-vb[](../../samples/word/insert_a_table/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, in this case doc. 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 and - as long as you use `using`. +[!include[Using Statement](../includes/using-statement.md)] ## Structure of a Table diff --git a/docs/word/how-to-retrieve-comments-from-a-word-processing-document.md b/docs/word/how-to-retrieve-comments-from-a-word-processing-document.md index c285d5ba..2adc581d 100644 --- a/docs/word/how-to-retrieve-comments-from-a-word-processing-document.md +++ b/docs/word/how-to-retrieve-comments-from-a-word-processing-document.md @@ -35,11 +35,7 @@ the Boolean parameter to `false`. [!code-vb[](../../samples/word/retrieve_comments/vb/Program.vb#snippet1)] *** -The `using` statement provides a recommended alternative to the .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`. - +[!include[Using Statement](../includes/using-statement.md)] -------------------------------------------------------------------------------- ## Comments Element From 37c5abd1ec0fe09c39ed25117565a9548d820b03 Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Thu, 8 Feb 2024 12:13:07 -0800 Subject: [PATCH 009/103] closes #217 --- ...picture-into-a-word-processing-document.md | 170 ++---------------- samples/samples.sln | 7 + samples/word/insert_a_picture/cs/Program.cs | 18 +- samples/word/insert_a_picture/vb/Program.vb | 103 ++++++----- 4 files changed, 98 insertions(+), 200 deletions(-) diff --git a/docs/word/how-to-insert-a-picture-into-a-word-processing-document.md b/docs/word/how-to-insert-a-picture-into-a-word-processing-document.md index 1b291772..51e51649 100644 --- a/docs/word/how-to-insert-a-picture-into-a-word-processing-document.md +++ b/docs/word/how-to-insert-a-picture-into-a-word-processing-document.md @@ -25,8 +25,8 @@ This topic shows how to use the classes in the Open XML SDK for Office to progra To open an existing document, instantiate the class as shown in the following `using` statement. In the same -statement, open the word processing file at the specified `filepath`by using the - +statement, open the word processing file at the specified `filepath` +by using the method, with the Boolean parameter set to `true` in order to enable editing the document. @@ -68,151 +68,24 @@ The following XML Schema fragment defines the contents of this element ## How the Sample Code Works -After you have opened the document, add the [ImagePart](/dotnet/api/documentformat.openxml.packaging.imagepart) object to the [MainDocumentPart](/dotnet/api/documentformat.openxml.packaging.maindocumentpart) object by using a file +After you have opened the document, add the +object to the object by using a file stream as shown in the following code segment. ### [C#](#tab/cs-1) -```csharp - MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart; - ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg); - using (FileStream stream = new FileStream(fileName, FileMode.Open)) - { - imagePart.FeedData(stream); - } - AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart)); -``` - +[!code-csharp[](../../samples/word/insert_a_picture/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-1) -```vb - Dim mainPart As MainDocumentPart = wordprocessingDocument.MainDocumentPart - Dim imagePart As ImagePart = mainPart.AddImagePart(ImagePartType.Jpeg) - Using stream As New FileStream(fileName, FileMode.Open) - imagePart.FeedData(stream) - End Using - AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart)) -``` +[!code-vb[](../../samples/word/insert_a_picture/vb/Program.vb#snippet2)] *** To add the image to the body, first define the reference of the image. -Then, append the reference to the body. The element should be in a [Run](/dotnet/api/documentformat.openxml.wordprocessing.run). +Then, append the reference to the body. The element should be in a . ### [C#](#tab/cs-2) -```csharp - // Define the reference of the image. - var element = - new Drawing( - new DW.Inline( - new DW.Extent() { Cx = 990000L, Cy = 792000L }, - new DW.EffectExtent() - { - LeftEdge = 0L, - TopEdge = 0L, - RightEdge = 0L, - BottomEdge = 0L - }, - new DW.DocProperties() - { - Id = (UInt32Value)1U, - Name = "Picture 1" - }, - new DW.NonVisualGraphicFrameDrawingProperties( - new A.GraphicFrameLocks() { NoChangeAspect = true }), - new A.Graphic( - new A.GraphicData( - new PIC.Picture( - new PIC.NonVisualPictureProperties( - new PIC.NonVisualDrawingProperties() - { - Id = (UInt32Value)0U, - Name = "New Bitmap Image.jpg" - }, - new PIC.NonVisualPictureDrawingProperties()), - new PIC.BlipFill( - new A.Blip( - new A.BlipExtensionList( - new A.BlipExtension() - { - Uri = - "{28A0092B-C50C-407E-A947-70E740481C1C}" - }) - ) - { - Embed = relationshipId, - CompressionState = - A.BlipCompressionValues.Print - }, - new A.Stretch( - new A.FillRectangle())), - new PIC.ShapeProperties( - new A.Transform2D( - new A.Offset() { X = 0L, Y = 0L }, - new A.Extents() { Cx = 990000L, Cy = 792000L }), - new A.PresetGeometry( - new A.AdjustValueList() - ) { Preset = A.ShapeTypeValues.Rectangle })) - ) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" }) - ) - { - DistanceFromTop = (UInt32Value)0U, - DistanceFromBottom = (UInt32Value)0U, - DistanceFromLeft = (UInt32Value)0U, - DistanceFromRight = (UInt32Value)0U, - EditId = "50D07946" - }); - - // Append the reference to the body. The element should be in - // a DocumentFormat.OpenXml.Wordprocessing.Run. - wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element))); -``` - +[!code-csharp[](../../samples/word/insert_a_picture/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-2) -```vb - ' Define the image reference. - Dim element = New Drawing( _ - New DW.Inline( _ - New DW.Extent() With {.Cx = 990000L, .Cy = 792000L}, _ - New DW.EffectExtent() With {.LeftEdge = 0L, .TopEdge = 0L, .RightEdge = 0L, .BottomEdge = 0L}, _ - New DW.DocProperties() With {.Id = CType(1UI, UInt32Value), .Name = "Picture1"}, _ - New DW.NonVisualGraphicFrameDrawingProperties( _ - New A.GraphicFrameLocks() With {.NoChangeAspect = True} _ - ), _ - New A.Graphic(New A.GraphicData( _ - New PIC.Picture( _ - New PIC.NonVisualPictureProperties( _ - New PIC.NonVisualDrawingProperties() With {.Id = 0UI, .Name = "Koala.jpg"}, _ - New PIC.NonVisualPictureDrawingProperties() _ - ), _ - New PIC.BlipFill( _ - New A.Blip( _ - New A.BlipExtensionList( _ - New A.BlipExtension() With {.Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}"}) _ - ) With {.Embed = relationshipId, .CompressionState = A.BlipCompressionValues.Print}, _ - New A.Stretch( _ - New A.FillRectangle() _ - ) _ - ), _ - New PIC.ShapeProperties( _ - New A.Transform2D( _ - New A.Offset() With {.X = 0L, .Y = 0L}, _ - New A.Extents() With {.Cx = 990000L, .Cy = 792000L}), _ - New A.PresetGeometry( _ - New A.AdjustValueList() _ - ) With {.Preset = A.ShapeTypeValues.Rectangle} _ - ) _ - ) _ - ) With {.Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"} _ - ) _ - ) With {.DistanceFromTop = 0UI, _ - .DistanceFromBottom = 0UI, _ - .DistanceFromLeft = 0UI, _ - .DistanceFromRight = 0UI} _ - ) - - ' Append the reference to the body, the element should be in - ' a DocumentFormat.OpenXml.Wordprocessing.Run. - wordDoc.MainDocumentPart.Document.Body.AppendChild(New Paragraph(New Run(element))) -``` +[!code-vb[](../../samples/word/insert_a_picture/vb/Program.vb#snippet3)] *** @@ -220,37 +93,26 @@ Then, append the reference to the body. The element should be in a [Run](/dotnet ## Sample Code The following code example adds a picture to an existing word document. -In your code, you can call the **InsertAPicture** method by passing in the path of +In your code, you can call the `InsertAPicture` method by passing in the path of the word document, and the path of the file that contains the picture. -For example, the following call inserts the picture "MyPic.jpg" into the -file "Word9.docx," located at the specified paths. +For example, the following call inserts the picture. ### [C#](#tab/cs-3) -```csharp - string document = @"C:\Users\Public\Documents\Word9.docx"; - string fileName = @"C:\Users\Public\Documents\MyPic.jpg"; - InsertAPicture(document, fileName); -``` - +[!code-csharp[](../../samples/word/insert_a_picture/cs/Program.cs#snippet4)] ### [Visual Basic](#tab/vb-3) -```vb - Dim document As String = "C:\Users\Public\Documents\Word9.docx" - Dim fileName As String = "C:\Users\Public\Documents\MyPic.jpg" - InsertAPicture(document, fileName) -``` +[!code-vb[](../../samples/word/insert_a_picture/vb/Program.vb#snippet4)] *** -After you run the code, look at the file "Word9.docx" to see the -inserted picture. +After you run the code, look at the file to see the inserted picture. The following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/insert_a_picture/cs/Program.cs)] +[!code-csharp[](../../samples/word/insert_a_picture/cs/Program.cs#snippet)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/insert_a_picture/vb/Program.vb)] +[!code-vb[](../../samples/word/insert_a_picture/vb/Program.vb#snippet)] -------------------------------------------------------------------------------- diff --git a/samples/samples.sln b/samples/samples.sln index 590ac98c..0d04415f 100644 --- a/samples/samples.sln +++ b/samples/samples.sln @@ -334,6 +334,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "working_with_tables_cs", "w EndProject Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "working_with_tables_vb", "word\working_with_tables\vb\working_with_tables_vb.vbproj", "{4EB1FCC9-E1E2-4D2A-ACF9-A3A31AA947A5}" EndProject +Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "insert_a_picture_vb", "word\insert_a_picture\vb\insert_a_picture_vb.vbproj", "{6170C4E1-A109-435A-BF59-026C85B3BD9C}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -980,6 +982,10 @@ Global {4EB1FCC9-E1E2-4D2A-ACF9-A3A31AA947A5}.Debug|Any CPU.Build.0 = Debug|Any CPU {4EB1FCC9-E1E2-4D2A-ACF9-A3A31AA947A5}.Release|Any CPU.ActiveCfg = Release|Any CPU {4EB1FCC9-E1E2-4D2A-ACF9-A3A31AA947A5}.Release|Any CPU.Build.0 = Release|Any CPU + {6170C4E1-A109-435A-BF59-026C85B3BD9C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6170C4E1-A109-435A-BF59-026C85B3BD9C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6170C4E1-A109-435A-BF59-026C85B3BD9C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6170C4E1-A109-435A-BF59-026C85B3BD9C}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -1144,6 +1150,7 @@ Global {72BE6D64-0AEB-4090-A6F9-B255D291BF14} = {7ACDC26B-C774-4004-8553-87E862D1E71F} {A43A75AB-D6B6-4D31-99F7-6951AFEF502D} = {D207D3D7-FD4D-4FD4-A7D0-79A82086FB6F} {4EB1FCC9-E1E2-4D2A-ACF9-A3A31AA947A5} = {D207D3D7-FD4D-4FD4-A7D0-79A82086FB6F} + {6170C4E1-A109-435A-BF59-026C85B3BD9C} = {D207D3D7-FD4D-4FD4-A7D0-79A82086FB6F} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {721B3030-08D7-4412-9087-D1CFBB3F5046} diff --git a/samples/word/insert_a_picture/cs/Program.cs b/samples/word/insert_a_picture/cs/Program.cs index 4d786ce0..786fe252 100644 --- a/samples/word/insert_a_picture/cs/Program.cs +++ b/samples/word/insert_a_picture/cs/Program.cs @@ -1,3 +1,4 @@ +// using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; @@ -7,17 +8,19 @@ using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing; using PIC = DocumentFormat.OpenXml.Drawing.Pictures; -InsertAPicture(args[0], args[1]); static void InsertAPicture(string document, string fileName) { + // using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(document, true)) + // { if (wordprocessingDocument.MainDocumentPart is null) { throw new ArgumentNullException("MainDocumentPart is null."); } + // MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart; ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg); @@ -28,11 +31,13 @@ static void InsertAPicture(string document, string fileName) } AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart)); + // } } static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId) { + // // Define the reference of the image. var element = new Drawing( @@ -104,4 +109,13 @@ static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId // Append the reference to body, the element should be in a Run. wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element))); -} \ No newline at end of file + // +} +// + +// +string documentPath = args[0]; +string picturePath = args[1]; + +InsertAPicture(documentPath, picturePath); +// diff --git a/samples/word/insert_a_picture/vb/Program.vb b/samples/word/insert_a_picture/vb/Program.vb index 5359cddc..462603d7 100644 --- a/samples/word/insert_a_picture/vb/Program.vb +++ b/samples/word/insert_a_picture/vb/Program.vb @@ -1,3 +1,4 @@ +' Imports System.IO Imports DocumentFormat.OpenXml Imports DocumentFormat.OpenXml.Packaging @@ -6,14 +7,24 @@ Imports A = DocumentFormat.OpenXml.Drawing Imports DW = DocumentFormat.OpenXml.Drawing.Wordprocessing Imports PIC = DocumentFormat.OpenXml.Drawing.Pictures -Module Program ` - Sub Main(args As String())` - End Sub` +Module Program + Sub Main(args As String()) + ' + Dim documentPath As String = args(0) + Dim picturePath As String = args(1) + + InsertAPicture(documentPath, picturePath) + ' + End Sub + + - - Public Sub InsertAPicture(ByVal document As String, ByVal fileName As String) + ' Using wordprocessingDocument As WordprocessingDocument = WordprocessingDocument.Open(document, True) + ' + + ' Dim mainPart As MainDocumentPart = wordprocessingDocument.MainDocumentPart Dim imagePart As ImagePart = mainPart.AddImagePart(ImagePartType.Jpeg) @@ -23,52 +34,56 @@ Module Program ` End Using AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart)) + ' End Using End Sub Private Sub AddImageToBody(ByVal wordDoc As WordprocessingDocument, ByVal relationshipId As String) + ' ' Define the reference of the image. - Dim element = New Drawing( _ - New DW.Inline( _ - New DW.Extent() With {.Cx = 990000L, .Cy = 792000L}, _ - New DW.EffectExtent() With {.LeftEdge = 0L, .TopEdge = 0L, .RightEdge = 0L, .BottomEdge = 0L}, _ - New DW.DocProperties() With {.Id = CType(1UI, UInt32Value), .Name = "Picture1"}, _ - New DW.NonVisualGraphicFrameDrawingProperties( _ - New A.GraphicFrameLocks() With {.NoChangeAspect = True} _ - ), _ - New A.Graphic(New A.GraphicData( _ - New PIC.Picture( _ - New PIC.NonVisualPictureProperties( _ - New PIC.NonVisualDrawingProperties() With {.Id = 0UI, .Name = "Koala.jpg"}, _ - New PIC.NonVisualPictureDrawingProperties() _ - ), _ - New PIC.BlipFill( _ - New A.Blip( _ - New A.BlipExtensionList( _ - New A.BlipExtension() With {.Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}"}) _ - ) With {.Embed = relationshipId, .CompressionState = A.BlipCompressionValues.Print}, _ - New A.Stretch( _ - New A.FillRectangle() _ - ) _ - ), _ - New PIC.ShapeProperties( _ - New A.Transform2D( _ - New A.Offset() With {.X = 0L, .Y = 0L}, _ - New A.Extents() With {.Cx = 990000L, .Cy = 792000L}), _ - New A.PresetGeometry( _ - New A.AdjustValueList() _ - ) With {.Preset = A.ShapeTypeValues.Rectangle} _ - ) _ - ) _ - ) With {.Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"} _ - ) _ - ) With {.DistanceFromTop = 0UI, _ - .DistanceFromBottom = 0UI, _ - .DistanceFromLeft = 0UI, _ - .DistanceFromRight = 0UI} _ + Dim element = New Drawing( + New DW.Inline( + New DW.Extent() With {.Cx = 990000L, .Cy = 792000L}, + New DW.EffectExtent() With {.LeftEdge = 0L, .TopEdge = 0L, .RightEdge = 0L, .BottomEdge = 0L}, + New DW.DocProperties() With {.Id = CType(1UI, UInt32Value), .Name = "Picture1"}, + New DW.NonVisualGraphicFrameDrawingProperties( + New A.GraphicFrameLocks() With {.NoChangeAspect = True} + ), + New A.Graphic(New A.GraphicData( + New PIC.Picture( + New PIC.NonVisualPictureProperties( + New PIC.NonVisualDrawingProperties() With {.Id = 0UI, .Name = "Koala.jpg"}, + New PIC.NonVisualPictureDrawingProperties() + ), + New PIC.BlipFill( + New A.Blip( + New A.BlipExtensionList( + New A.BlipExtension() With {.Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}"}) + ) With {.Embed = relationshipId, .CompressionState = A.BlipCompressionValues.Print}, + New A.Stretch( + New A.FillRectangle() + ) + ), + New PIC.ShapeProperties( + New A.Transform2D( + New A.Offset() With {.X = 0L, .Y = 0L}, + New A.Extents() With {.Cx = 990000L, .Cy = 792000L}), + New A.PresetGeometry( + New A.AdjustValueList() + ) With {.Preset = A.ShapeTypeValues.Rectangle} + ) + ) + ) With {.Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"} + ) + ) With {.DistanceFromTop = 0UI, + .DistanceFromBottom = 0UI, + .DistanceFromLeft = 0UI, + .DistanceFromRight = 0UI} ) ' Append the reference to body, the element should be in a Run. wordDoc.MainDocumentPart.Document.Body.AppendChild(New Paragraph(New Run(element))) + ' End Sub -End Module \ No newline at end of file +End Module +' From 428e4e479f5b1f67ec31703cfe7f479eaf0e2c03 Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Thu, 8 Feb 2024 13:52:26 -0800 Subject: [PATCH 010/103] closes #216 --- ...comment-into-a-word-processing-document.md | 203 +++++------------- samples/word/insert_a_comment/cs/Program.cs | 24 ++- samples/word/insert_a_comment/vb/Program.vb | 23 +- 3 files changed, 99 insertions(+), 151 deletions(-) diff --git a/docs/word/how-to-insert-a-comment-into-a-word-processing-document.md b/docs/word/how-to-insert-a-comment-into-a-word-processing-document.md index b010c28b..dc355027 100644 --- a/docs/word/how-to-insert-a-comment-into-a-word-processing-document.md +++ b/docs/word/how-to-insert-a-comment-into-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: 02/08/2024 ms.localizationpriority: medium --- # Insert a comment into a word processing document @@ -25,27 +25,16 @@ word processing document. -------------------------------------------------------------------------------- ## Open the Existing Document for Editing To open an existing document, instantiate the class as shown in -the following **using** statement. In the same +the following `using` statement. In the same statement, open the word processing file at the specified *filepath* by -using the [Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) method, with the -Boolean parameter set to **true** to enable +using the +method, with the Boolean parameter set to `true` to enable editing in the document. ### [C#](#tab/cs-0) -```csharp - using (WordprocessingDocument document = - WordprocessingDocument.Open(filepath, true)) - { - // Insert other code here. - } -``` - +[!code-csharp[](../../samples/word/insert_a_comment/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - Using document As WordprocessingDocument = WordprocessingDocument.Open(filepath, True) - ' Insert other code here. - End Using -``` +[!code-vb[](../../samples/word/insert_a_comment/vb/Program.vb#snippet1)] *** [!include[Using Statement](../includes/using-statement.md)] @@ -53,88 +42,47 @@ editing in the document. -------------------------------------------------------------------------------- ## How the Sample Code Works + After you open the document, you can find the first paragraph to attach -a comment. The code finds the first paragraph by calling the -[First](/dotnet/api/system.linq.enumerable.first) +a comment. The code finds the first paragraph by calling the extension method on all the descendant elements of the document element -that are of type [Paragraph](/dotnet/api/documentformat.openxml.wordprocessing.paragraph). The **First** method is a member -of the -[System.Linq.Enumerable](/dotnet/api/system.linq.enumerable) -class. The **System.Linq.Enumerable** class -provides extension methods for objects that implement the -[System.Collections.Generic.IEnumerable](/dotnet/api/system.collections.generic.ienumerable-1) -interface. +that are of type . The `First` method is a member +of the class. The `System.Linq.Enumerable` class +provides extension methods for objects that implement the interface. ### [C#](#tab/cs-1) -```csharp - Paragraph firstParagraph = document.MainDocumentPart.Document.Descendants().First(); - Comments comments = null; - string id = "0"; -``` - +[!code-csharp[](../../samples/word/insert_a_comment/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-1) -```vb - Dim firstParagraph As Paragraph = document.MainDocumentPart.Document.Descendants(Of Paragraph)().First() - Dim comments As Comments = Nothing - Dim id As String = "0" -``` +[!code-vb[](../../samples/word/insert_a_comment/vb/Program.vb#snippet2)] *** -The code first determines whether a [WordprocessingCommentsPart](/dotnet/api/documentformat.openxml.packaging.wordprocessingcommentspart) part exists. To -do this, call the [MainDocumentPart](/dotnet/api/documentformat.openxml.packaging.maindocumentpart) generic method, **GetPartsCountOfType**, and specify a kind of **WordprocessingCommentsPart**. +The code first determines whether a +part exists. To do this, call the generic method, +`GetPartsCountOfType`, and specify a kind of `WordprocessingCommentsPart`. -If a **WordprocessingCommentsPart** part -exists, the code obtains a new **Id** value for -the [Comment](/dotnet/api/documentformat.openxml.wordprocessing.comment) object that it will add to the -existing **WordprocessingCommentsPart** [Comments](/dotnet/api/documentformat.openxml.wordprocessing.comments) collection object. It does this by -finding the highest **Id** attribute value -given to a **Comment** in the **Comments** collection object, incrementing the -value by one, and then storing that as the **Id** value.If no **WordprocessingCommentsPart** part exists, the code -creates one using the [AddNewPart\()](/dotnet/api/documentformat.openxml.packaging.openxmlpartcontainer.addnewpart) method of the [MainDocumentPart](/dotnet/api/documentformat.openxml.packaging.maindocumentpart) object and then adds a -**Comments** collection object to it. +If a `WordprocessingCommentsPart` part exists, the code obtains a new `Id` value for +the object that it will add to the +existing `WordprocessingCommentsPart` +collection object. It does this by finding the highest `Id` attribute value +given to a `Comment` in the `Comments` collection object, incrementing the +value by one, and then storing that as the `Id` value.If no `WordprocessingCommentsPart` part exists, the code +creates one using the +method of the object and then adds a +`Comments` collection object to it. ### [C#](#tab/cs-2) -```csharp - if (document.MainDocumentPart.GetPartsCountOfType() > 0) - { - comments = - document.MainDocumentPart.WordprocessingCommentsPart.Comments; - if (comments.HasChildren) - { - id = (comments.Descendants().Select(e => int.Parse(e.Id.Value)).Max() + 1).ToString(); - } - } - else - { - WordprocessingCommentsPart commentPart = - document.MainDocumentPart.AddNewPart(); - commentPart.Comments = new Comments(); - comments = commentPart.Comments; - } -``` - +[!code-csharp[](../../samples/word/insert_a_comment/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-2) -```vb - If document.MainDocumentPart.GetPartsCountOfType(Of WordprocessingCommentsPart)() > 0 Then - comments = document.MainDocumentPart.WordprocessingCommentsPart.Comments - If comments.HasChildren Then - id = comments.Descendants(Of Comment)().Select(Function(e) e.Id.Value).Max() - End If - Else - Dim commentPart As WordprocessingCommentsPart = document.MainDocumentPart.AddNewPart(Of WordprocessingCommentsPart)() - commentPart.Comments = New Comments() - comments = commentPart.Comments - End If -``` +[!code-vb[](../../samples/word/insert_a_comment/vb/Program.vb#snippet3)] *** -The **Comment** and **Comments** objects represent comment and comments -elements, respectively, in the Open XML Wordprocessing schema. A **Comment** must be added to a **Comments** object so the code first instantiates a -**Comments** object (using the string arguments -**author**, **initials**, -and **comments** that were passed in to the **AddCommentOnFirstParagraph** method). +The `Comment` and `Comments` objects represent comment and comments +elements, respectively, in the Open XML Wordprocessing schema. A `Comment` +must be added to a `Comments` object so the code first instantiates a +`Comments` object (using the string arguments `author`, `initials`, +and `comments` that were passed in to the `AddCommentOnFirstParagraph` method). The comment is represented by the following WordprocessingML code example. . @@ -145,31 +93,15 @@ example. . ``` -The code then appends the **Comment** to the -**Comments** object and saves the changes. This +The code then appends the `Comment` to the `Comments` object and saves the changes. This creates the required XML document object model (DOM) tree structure in -memory which consists of a **comments** parent -element with **comment** child elements under +memory which consists of a `comments` parent element with `comment` child elements under it. ### [C#](#tab/cs-3) -```csharp - Paragraph p = new Paragraph(new Run(new Text(comment))); - Comment cmt = new Comment() { Id = id, - Author = author, Initials = initials, Date = DateTime.Now }; - cmt.AppendChild(p); - comments.AppendChild(cmt); - comments.Save(); -``` - +[!code-csharp[](../../samples/word/insert_a_comment/cs/Program.cs#snippet4)] ### [Visual Basic](#tab/vb-3) -```vb - Dim p As New Paragraph(New Run(New Text(comment))) - Dim cmt As New Comment() With {.Id = id, .Author = author, .Initials = initials, .Date = Date.Now} - cmt.AppendChild(p) - comments.AppendChild(cmt) - comments.Save() -``` +[!code-vb[](../../samples/word/insert_a_comment/vb/Program.vb#snippet4)] *** @@ -184,18 +116,17 @@ comments part in a WordprocessingML document. ``` -With the **Comment** object instantiated, the -code associates the **Comment** with a range in -the Wordprocessing document. [CommentRangeStart](/dotnet/api/documentformat.openxml.wordprocessing.commentrangestart) and [CommentRangeEnd](/dotnet/api/documentformat.openxml.wordprocessing.commentrangeend) objects correspond to the -**commentRangeStart** and **commentRangeEnd** elements in the Open XML -Wordprocessing schema. A **CommentRangeStart** -object is given as the argument to the [InsertBefore\(T, OpenXmlElement)](/dotnet/api/documentformat.openxml.openxmlcompositeelement.insertbefore) method -of the [Paragraph](/dotnet/api/documentformat.openxml.wordprocessing.paragraph) object and a **CommentRangeEnd** object is passed to the [InsertAfter\(T, OpenXmlElement)](/dotnet/api/documentformat.openxml.openxmlcompositeelement.insertafter) method. -This creates a comment range that extends from immediately before the -first character of the first paragraph in the Wordprocessing document to -immediately after the last character of the first paragraph. - -A [CommentReference](/dotnet/api/documentformat.openxml.wordprocessing.commentreference) object represents a +With the **Comment** object instantiated, the code associates the **Comment** with a range in +the Wordprocessing document. and + objects correspond to the +**commentRangeStart** and **commentRangeEnd** elements in the Open XML Wordprocessing schema. +A **CommentRangeStart** object is given as the argument to the +method of the object and a **CommentRangeEnd** +object is passed to the method. +This creates a comment range that extends from immediately before the first character of the first paragraph +in the Wordprocessing document to immediately after the last character of the first paragraph. + +A object represents a **commentReference** element in the Open XML Wordprocessing schema. A commentReference links a specific comment in the **WordprocessingCommentsPart** part (the Comments.xml file in the Wordprocessing package) to a specific location in the @@ -207,27 +138,12 @@ a given comment, so the commentReference **id** attribute must match the comment **id** attribute value that it links to. In the sample, the code adds a **commentReference** element by using the API, and instantiates a **CommentReference** object, -specifying the **Id** value, and then adds it to a [Run](/dotnet/api/documentformat.openxml.wordprocessing.run) object. +specifying the **Id** value, and then adds it to a object. ### [C#](#tab/cs-4) -```csharp - firstParagraph.InsertBefore(new CommentRangeStart() - { Id = id }, firstParagraph.GetFirstChild()); - - var cmtEnd = firstParagraph.InsertAfter(new CommentRangeEnd() - { Id = id }, firstParagraph.Elements().Last()); - - firstParagraph.InsertAfter(new Run(new CommentReference() { Id = id }), cmtEnd); -``` - +[!code-csharp[](../../samples/word/insert_a_comment/cs/Program.cs#snippet5)] ### [Visual Basic](#tab/vb-4) -```vb - firstParagraph.InsertBefore(New CommentRangeStart() With {.Id = id}, firstParagraph.GetFirstChild(Of Run)()) - - Dim cmtEnd = firstParagraph.InsertAfter(New CommentRangeEnd() With {.Id = id}, firstParagraph.Elements(Of Run)().Last()) - - firstParagraph.InsertAfter(New Run(New CommentReference() With {.Id = id}), cmtEnd) -``` +[!code-vb[](../../samples/word/insert_a_comment/vb/Program.vb#snippet5)] *** @@ -235,31 +151,22 @@ specifying the **Id** value, and then adds it to a [Run](/dotnet/api/documentfor ## Sample Code The following code example shows how to create a comment and associate it with a range in a word processing document. To call the method **AddCommentOnFirstParagraph** pass in the path of -the document, your name, your initials, and the comment text. For -example, the following call to the **AddCommentOnFirstParagraph** method writes the -comment "This is my comment." in the file "Word8.docx." +the document, your name, your initials, and the comment text. ### [C#](#tab/cs-5) -```csharp - AddCommentOnFirstParagraph(@"C:\Users\Public\Documents\Word8.docx", - author, initials, "This is my comment."); -``` - +[!code-csharp[](../../samples/word/insert_a_comment/cs/Program.cs#snippet6)] ### [Visual Basic](#tab/vb-5) -```vb - AddCommentOnFirstParagraph("C:\Users\Public\Documents\Word8.docx", _ - author, initials, comment) -``` +[!code-vb[](../../samples/word/insert_a_comment/vb/Program.vb#snippet6)] *** Following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/insert_a_comment/cs/Program.cs)] +[!code-csharp[](../../samples/word/insert_a_comment/cs/Program.cs#snippet)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/insert_a_comment/vb/Program.vb)] +[!code-vb[](../../samples/word/insert_a_comment/vb/Program.vb#snippet)] -------------------------------------------------------------------------------- ## See also diff --git a/samples/word/insert_a_comment/cs/Program.cs b/samples/word/insert_a_comment/cs/Program.cs index e1b9e924..f7e0c890 100644 --- a/samples/word/insert_a_comment/cs/Program.cs +++ b/samples/word/insert_a_comment/cs/Program.cs @@ -1,16 +1,18 @@ +// using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System; using System.Linq; -AddCommentOnFirstParagraph(args[0], args[1], args[2], args[3]); // Insert a comment on the first paragraph. static void AddCommentOnFirstParagraph(string fileName, string author, string initials, string comment) { // Use the file name and path passed in as an // argument to open an existing Wordprocessing document. + // using (WordprocessingDocument document = WordprocessingDocument.Open(fileName, true)) + // { if (document.MainDocumentPart is null/* || document.MainDocumentPart.WordprocessingCommentsPart is null*/) { @@ -20,12 +22,15 @@ static void AddCommentOnFirstParagraph(string fileName, string author, string in WordprocessingCommentsPart wordprocessingCommentsPart = document.MainDocumentPart.WordprocessingCommentsPart ?? document.MainDocumentPart.AddNewPart(); // Locate the first paragraph in the document. + // Paragraph firstParagraph = document.MainDocumentPart.Document.Descendants().First(); wordprocessingCommentsPart.Comments ??= new Comments(); string id = "0"; + // // Verify that the document contains a // WordProcessingCommentsPart part; if not, add a new one. + // if (document.MainDocumentPart.GetPartsOfType().Count() > 0) { if (wordprocessingCommentsPart.Comments.HasChildren) @@ -45,8 +50,10 @@ static void AddCommentOnFirstParagraph(string fileName, string author, string in .Max() + 1).ToString(); } } + // // Compose a new Comment and add it to the Comments part. + // Paragraph p = new Paragraph(new Run(new Text(comment))); Comment cmt = new Comment() @@ -59,9 +66,11 @@ static void AddCommentOnFirstParagraph(string fileName, string author, string in cmt.AppendChild(p); wordprocessingCommentsPart.Comments.AppendChild(cmt); wordprocessingCommentsPart.Comments.Save(); + // // Specify the text range for the Comment. // Insert the new CommentRangeStart before the first run of paragraph. + // firstParagraph.InsertBefore(new CommentRangeStart() { Id = id }, firstParagraph.GetFirstChild()); @@ -71,5 +80,16 @@ static void AddCommentOnFirstParagraph(string fileName, string author, string in // Compose a run with CommentReference and insert it. firstParagraph.InsertAfter(new Run(new CommentReference() { Id = id }), cmtEnd); + // } -} \ No newline at end of file +} +// + +// +string fileName = args[0]; +string author = args[1]; +string initials = args[2]; +string comment = args[3]; + +AddCommentOnFirstParagraph(fileName, author, initials, comment); +// diff --git a/samples/word/insert_a_comment/vb/Program.vb b/samples/word/insert_a_comment/vb/Program.vb index c556b09c..323ea624 100644 --- a/samples/word/insert_a_comment/vb/Program.vb +++ b/samples/word/insert_a_comment/vb/Program.vb @@ -1,8 +1,17 @@ +' Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Wordprocessing Module Program Sub Main(args As String()) + ' + Dim fileName As String = args(0) + Dim author As String = args(1) + Dim initials As String = args(2) + Dim comment As String = args(3) + + AddCommentOnFirstParagraph(fileName, author, initials, comment) + ' End Sub @@ -11,14 +20,20 @@ Module Program Public Sub AddCommentOnFirstParagraph(ByVal fileName As String, ByVal author As String, ByVal initials As String, ByVal comment As String) ' Use the file name and path passed in as an ' argument to open an existing Wordprocessing document. + ' Using document As WordprocessingDocument = WordprocessingDocument.Open(fileName, True) + ' + ' Locate the first paragraph in the document. + ' Dim firstParagraph As Paragraph = document.MainDocumentPart.Document.Descendants(Of Paragraph)().First() Dim comments As Comments = Nothing Dim id As String = "0" + ' ' Verify that the document contains a ' WordProcessingCommentsPart part; if not, add a new one. + ' If document.MainDocumentPart.GetPartsOfType(Of WordprocessingCommentsPart).Count() > 0 Then comments = document.MainDocumentPart.WordprocessingCommentsPart.Comments If comments.HasChildren Then @@ -31,16 +46,20 @@ Module Program commentPart.Comments = New Comments() comments = commentPart.Comments End If + ' ' Compose a new Comment and add it to the Comments part. + ' Dim p As New Paragraph(New Run(New Text(comment))) Dim cmt As New Comment() With {.Id = id, .Author = author, .Initials = initials, .Date = DateTime.Now} cmt.AppendChild(p) comments.AppendChild(cmt) comments.Save() + ' ' Specify the text range for the Comment. ' Insert the new CommentRangeStart before the first run of paragraph. + ' firstParagraph.InsertBefore(New CommentRangeStart() With {.Id = id}, firstParagraph.GetFirstChild(Of Run)()) ' Insert the new CommentRangeEnd after last run of paragraph. @@ -48,6 +67,8 @@ Module Program ' Compose a run with CommentReference and insert it. firstParagraph.InsertAfter(New Run(New CommentReference() With {.Id = id}), cmtEnd) + ' End Using End Sub -End Module \ No newline at end of file +End Module +' From b2fc6f1400e39febc1a0e2338b1d0fdc0dda15d9 Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Fri, 9 Feb 2024 12:11:59 -0800 Subject: [PATCH 011/103] closes #215 --- ...-styles-from-a-word-processing-document.md | 186 ++++-------------- samples/word/extract_styles/cs/Program.cs | 61 ++++-- samples/word/extract_styles/vb/Program.vb | 44 ++++- 3 files changed, 119 insertions(+), 172 deletions(-) diff --git a/docs/word/how-to-extract-styles-from-a-word-processing-document.md b/docs/word/how-to-extract-styles-from-a-word-processing-document.md index c75f4d25..15afc193 100644 --- a/docs/word/how-to-extract-styles-from-a-word-processing-document.md +++ b/docs/word/how-to-extract-styles-from-a-word-processing-document.md @@ -12,16 +12,15 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 06/28/2021 +ms.date: 02/09/2024 ms.localizationpriority: medium --- # Extract styles from a word processing document This topic shows how to use the classes in the Open XML SDK for Office to programmatically extract the styles or stylesWithEffects part -from a word processing document to an -[XDocument](/dotnet/api/system.xml.linq.xdocument) -instance. It contains an example **ExtractStylesPart** method to +from a word processing document to an +instance. It contains an example `ExtractStylesPart` method to illustrate this task. @@ -30,7 +29,7 @@ illustrate this task. ## ExtractStylesPart Method -You can use the **ExtractStylesPart** sample method to retrieve an **XDocument** instance that contains the styles or +You can use the `ExtractStylesPart` sample method to retrieve an `XDocument` instance that contains the styles or stylesWithEffects part for a Microsoft Word document. Be aware that in a document created in Word 2010, there will only be a single styles part; Word 2013+ adds a second stylesWithEffects part. To provide for "round-tripping" a document from Word 2013+ to Word @@ -42,29 +41,20 @@ Word 2013+ adds to the document.) You (and your application) must interpret the results of retrieving the styles or stylesWithEffects part. -The **ExtractStylesPart** procedure accepts a two parameters: the first +The `ExtractStylesPart` procedure accepts a two parameters: the first parameter contains a string indicating the path of the file from which you want to extract styles, and the second indicates whether you want to retrieve the styles part, or the newer stylesWithEffects part (basically, you must call this procedure two times for Word 2013+ -documents, retrieving each the part). The procedure returns an **XDocument** instance that contains the complete +documents, retrieving each the part). The procedure returns an `XDocument` instance that contains the complete styles or stylesWithEffects part that you requested, with all the style information for the document (or a null reference, if the part you requested does not exist). ### [C#](#tab/cs-0) -```csharp - public static XDocument ExtractStylesPart( - string fileName, - bool getStylesWithEffectsPart = true) -``` - +[!code-csharp[](../../samples/word/extract_styles/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - Public Function ExtractStylesPart( - ByVal fileName As String, - Optional ByVal getStylesWithEffectsPart As Boolean = True) As XDocument -``` +[!code-vb[](../../samples/word/extract_styles/vb/Program.vb#snippet1)] *** @@ -77,38 +67,16 @@ The complete code listing for the method can be found in the [Sample Code](#samp To call the sample method, pass a string for the first parameter that contains the file name of the document from which to extract the styles, and a Boolean for the second parameter that specifies whether the type -of part to retrieve is the styleWithEffects part (**true**), or the styles part (**false**). The following sample code shows an example. -When you have the **XDocument** instance you +of part to retrieve is the styleWithEffects part (`true`), or the styles part (`false`). The following sample code shows an example. +When you have the `XDocument` instance you can do what you want with it; in the following sample code the content -of the **XDocument** instance is displayed to +of the `XDocument` instance is displayed to the console. ### [C#](#tab/cs-1) -```csharp - string filename = @"C:\Users\Public\Documents\StylesFrom.docx"; - - // Retrieve the StylesWithEffects part. You could pass false in the - // second parameter to retrieve the Styles part instead. - var styles = ExtractStylesPart(filename, true); - - // If the part was retrieved, send the contents to the console. - if (styles != null) - Console.WriteLine(styles.ToString()); -``` - +[!code-csharp[](../../samples/word/extract_styles/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-1) -```vb - Dim filename As String = "C:\Users\Public\Documents\StylesFrom.docx" - - ' Retrieve the stylesWithEffects part. You could pass False - ' in the second parameter to retrieve the styles part instead. - Dim styles = ExtractStylesPart(filename, True) - - ' If the part was retrieved, send the contents to the console. - If styles IsNot Nothing Then - Console.WriteLine(styles.ToString()) - End If -``` +[!code-vb[](../../samples/word/extract_styles/vb/Program.vb#snippet2)] *** @@ -116,92 +84,32 @@ the console. ## How the Code Works -The code starts by creating a variable named **styles** that the method returns before it exits. - -### [C#](#tab/cs-2) -```csharp - // Declare a variable to hold the XDocument. - XDocument styles = null; - // Code removed here... - // Return the XDocument instance. - return styles; -``` - -### [Visual Basic](#tab/vb-2) -```vb - ' Declare a variable to hold the XDocument. - Dim styles As XDocument = Nothing - ' Code removed here... - ' Return the XDocument instance. - Return styles -``` -*** - - -The code continues by opening the document by using the [Open](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) method and indicating that the -document should be open for read-only access (the final false -parameter). Given the open document, the code uses the [MainDocumentPart](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.maindocumentpart) property to navigate to -the main document part, and then prepares a variable named **stylesPart** to hold a reference to the styles part. +The code starts by creating a variable named `styles` to contain the return value for the method. +The code continues by opening the document by using the +method and indicating that the document should be open for read-only access (the final false +parameter). Given the open document, the code uses the +property to navigate to the main document part, and then prepares a variable named `stylesPart` to hold a reference to the styles part. ### [C#](#tab/cs-3) -```csharp - // Open the document for read access and get a reference. - using (var document = - WordprocessingDocument.Open(fileName, false)) - { - // Get a reference to the main document part. - var docPart = document.MainDocumentPart; - - // Assign a reference to the appropriate part to the - // stylesPart variable. - StylesPart stylesPart = null; - // Code removed here... - } -``` - +[!code-csharp[](../../samples/word/extract_styles/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-3) -```vb - ' Open the document for read access and get a reference. - Using document = WordprocessingDocument.Open(fileName, False) - - ' Get a reference to the main document part. - Dim docPart = document.MainDocumentPart - - ' Assign a reference to the appropriate part to the - ' stylesPart variable. - Dim stylesPart As StylesPart = Nothing - ' Code removed here... - End Using -``` +[!code-vb[](../../samples/word/extract_styles/vb/Program.vb#snippet3)] *** - --------------------------------------------------------------------------------- ## Find the Correct Styles Part The code next retrieves a reference to the requested styles part by -using the **getStylesWithEffectsPart** Boolean -parameter. Based on this value, the code retrieves a specific property -of the **docPart** variable, and stores it in the -**stylesPart** variable. +using the `getStylesWithEffectsPart` parameter. +Based on this value, the code retrieves a specific property +of the `docPart` variable, and stores it in the +`stylesPart` variable. ### [C#](#tab/cs-4) -```csharp - if (getStylesWithEffectsPart) - stylesPart = docPart.StylesWithEffectsPart; - else - stylesPart = docPart.StyleDefinitionsPart; -``` - +[!code-csharp[](../../samples/word/extract_styles/cs/Program.cs#snippet4)] ### [Visual Basic](#tab/vb-4) -```vb - If getStylesWithEffectsPart Then - stylesPart = docPart.StylesWithEffectsPart - Else - stylesPart = docPart.StyleDefinitionsPart - End If -``` +[!code-vb[](../../samples/word/extract_styles/vb/Program.vb#snippet4)] *** @@ -210,40 +118,16 @@ of the **docPart** variable, and stores it in the ## Retrieve the Part Contents If the requested styles part exists, the code must return the contents -of the part in an **XDocument** instance. Each -part provides a [GetStream](/dotnet/api/documentformat.openxml.packaging.openxmlpart.getstream) method, which returns a Stream. -The code passes the Stream instance to the -[XmlNodeReader.Create](/dotnet/api/system.xml.xmlreader.create) -method, and then calls the -[XDocument.Load](/dotnet/api/system.xml.linq.xdocument.load) -method, passing the **XmlNodeReader** as a -parameter. +of the part in an `XDocument` instance. Each part provides a + method, which returns a Stream. +The code passes the Stream instance to the +method, and then calls the +method, passing the `XmlNodeReader` as a parameter. ### [C#](#tab/cs-5) -```csharp - // If the part exists, read it into the XDocument. - if (stylesPart != null) - { - using (var reader = XmlNodeReader.Create( - stylesPart.GetStream(FileMode.Open, FileAccess.Read))) - { - // Create the XDocument. - styles = XDocument.Load(reader); - } - } -``` - +[!code-csharp[](../../samples/word/extract_styles/cs/Program.cs#snippet5)] ### [Visual Basic](#tab/vb-5) -```vb - ' If the part exists, read it into the XDocument. - If stylesPart IsNot Nothing Then - Using reader = XmlNodeReader.Create( - stylesPart.GetStream(FileMode.Open, FileAccess.Read)) - ' Create the XDocument: - styles = XDocument.Load(reader) - End Using - End If -``` +[!code-vb[](../../samples/word/extract_styles/vb/Program.vb#snippet5)] *** @@ -254,10 +138,10 @@ parameter. The following is the complete **ExtractStylesPart** code sample in C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/extract_styles/cs/Program.cs)] +[!code-csharp[](../../samples/word/extract_styles/cs/Program.cs#snippet)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/extract_styles/vb/Program.vb)] +[!code-vb[](../../samples/word/extract_styles/vb/Program.vb#snippet)] --------------------------------------------------------------------------------- diff --git a/samples/word/extract_styles/cs/Program.cs b/samples/word/extract_styles/cs/Program.cs index 516e7c86..f7b9e2a5 100644 --- a/samples/word/extract_styles/cs/Program.cs +++ b/samples/word/extract_styles/cs/Program.cs @@ -1,29 +1,28 @@ +// using DocumentFormat.OpenXml.Packaging; using System; using System.IO; using System.Xml; using System.Xml.Linq; -if (args is [{ } fileName, { } getStyleWithEffectsPart]) -{ - ExtractStylesPart(fileName, getStyleWithEffectsPart); -} -else if (args is [{ } fileName2]) -{ - ExtractStylesPart(fileName2); -} // Extract the styles or stylesWithEffects part from a // word processing document as an XDocument instance. -static XDocument ExtractStylesPart(string fileName, string getStylesWithEffectsPart = "true") +// +static XDocument? ExtractStylesPart(string fileName, string getStylesWithEffectsPart = "true") +// { + // // Declare a variable to hold the XDocument. XDocument? styles = null; // Open the document for read access and get a reference. using (var document = WordprocessingDocument.Open(fileName, false)) { - if (document.MainDocumentPart is null || document.MainDocumentPart.StyleDefinitionsPart is null || document.MainDocumentPart.StylesWithEffectsPart is null) + if ( + document.MainDocumentPart is null || + (document.MainDocumentPart.StyleDefinitionsPart is null && document.MainDocumentPart.StylesWithEffectsPart is null) + ) { throw new ArgumentNullException("MainDocumentPart and/or one or both of the Styles parts is null."); } @@ -34,17 +33,51 @@ static XDocument ExtractStylesPart(string fileName, string getStylesWithEffectsP // Assign a reference to the appropriate part to the // stylesPart variable. StylesPart? stylesPart = null; + // + // if (getStylesWithEffectsPart.ToLower() == "true") + { stylesPart = docPart.StylesWithEffectsPart; + } else + { stylesPart = docPart.StyleDefinitionsPart; + } + // - using var reader = XmlNodeReader.Create(stylesPart.GetStream(FileMode.Open, FileAccess.Read)); + // + if (stylesPart is not null) + { + using var reader = XmlNodeReader.Create(stylesPart.GetStream(FileMode.Open, FileAccess.Read)); - // Create the XDocument. - styles = XDocument.Load(reader); + // Create the XDocument. + styles = XDocument.Load(reader); + } + // } // Return the XDocument instance. return styles; -} \ No newline at end of file +} +// + +// +if (args is [{ } fileName, { } getStyleWithEffectsPart]) +{ + var styles = ExtractStylesPart(fileName, getStyleWithEffectsPart); + + if (styles is not null) + { + Console.WriteLine(styles.ToString()); + } +} +else if (args is [{ } fileName2]) +{ + var styles = ExtractStylesPart(fileName2); + + if (styles is not null) + { + Console.WriteLine(styles.ToString()); + } +} +// diff --git a/samples/word/extract_styles/vb/Program.vb b/samples/word/extract_styles/vb/Program.vb index 6a182926..6926357f 100644 --- a/samples/word/extract_styles/vb/Program.vb +++ b/samples/word/extract_styles/vb/Program.vb @@ -1,19 +1,41 @@ +' Imports System.IO Imports System.Xml Imports DocumentFormat.OpenXml.Packaging Module Program Sub Main(args As String()) + ' + If args.Length >= 2 Then + Dim fileName As String = args(0) + Dim getStyleWithEffectsPart As String = args(1) + + Dim styles As XDocument = ExtractStylesPart(fileName, getStyleWithEffectsPart) + + If styles IsNot Nothing Then + Console.WriteLine(styles.ToString()) + End If + ElseIf args.Length = 1 Then + Dim fileName As String = args(0) + + Dim styles As XDocument = ExtractStylesPart(fileName) + + If styles IsNot Nothing Then + Console.WriteLine(styles.ToString()) + End If + End If + ' End Sub ' Extract the styles or stylesWithEffects part from a ' word processing document as an XDocument instance. - Public Function ExtractStylesPart( - ByVal fileName As String, - Optional ByVal getStylesWithEffectsPart As Boolean = True) As XDocument + ' + Public Function ExtractStylesPart(ByVal fileName As String, Optional ByVal getStylesWithEffectsPart As String = "true") As XDocument + ' + ' ' Declare a variable to hold the XDocument. Dim styles As XDocument = Nothing @@ -26,22 +48,30 @@ Module Program ' Assign a reference to the appropriate part to the ' stylesPart variable. Dim stylesPart As StylesPart = Nothing - If getStylesWithEffectsPart Then + ' + + ' + If getStylesWithEffectsPart.ToLower() = "true" Then stylesPart = docPart.StylesWithEffectsPart Else stylesPart = docPart.StyleDefinitionsPart End If + ' + ' ' If the part exists, read it into the XDocument. If stylesPart IsNot Nothing Then - Using reader = XmlNodeReader.Create( - stylesPart.GetStream(FileMode.Open, FileAccess.Read)) + Using reader = XmlNodeReader.Create(stylesPart.GetStream(FileMode.Open, FileAccess.Read)) + ' Create the XDocument: styles = XDocument.Load(reader) End Using End If End Using + ' + ' Return the XDocument instance. Return styles End Function -End Module \ No newline at end of file +End Module +' From 367e9343951c38a41b881d6a2169373194bf1b3c Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Fri, 9 Feb 2024 15:42:28 -0800 Subject: [PATCH 012/103] closes #214 --- ...ic-author-in-a-word-processing-document.md | 258 ++++-------------- .../cs/Program.cs | 76 ++++-- .../vb/Program.vb | 77 ++++-- 3 files changed, 161 insertions(+), 250 deletions(-) diff --git a/docs/word/how-to-delete-comments-by-all-or-a-specific-author-in-a-word-processing-document.md b/docs/word/how-to-delete-comments-by-all-or-a-specific-author-in-a-word-processing-document.md index c8ee6ffa..c2bcc55f 100644 --- a/docs/word/how-to-delete-comments-by-all-or-a-specific-author-in-a-word-processing-document.md +++ b/docs/word/how-to-delete-comments-by-all-or-a-specific-author-in-a-word-processing-document.md @@ -12,7 +12,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 06/28/2021 +ms.date: 02/09/2024 ms.localizationpriority: medium --- # Delete comments by all or a specific author in a word processing document @@ -20,7 +20,7 @@ ms.localizationpriority: medium This topic shows how to use the classes in the Open XML SDK for Office to programmatically delete comments by all or a specific author in a word processing document, without having to load the document into -Microsoft Word. It contains an example **DeleteComments** method to illustrate this task. +Microsoft Word. It contains an example `DeleteComments` method to illustrate this task. @@ -28,7 +28,7 @@ Microsoft Word. It contains an example **DeleteComments** method to illustrate t ## DeleteComments Method -You can use the **DeleteComments** method to +You can use the `DeleteComments` method to delete all of the comments from a word processing document, or only those written by a specific author. As shown in the following code, the method accepts two parameters that indicate the name of the document to @@ -38,20 +38,9 @@ deletes comments written by the specified author. If you do not supply an author name, the code deletes all comments. ### [C#](#tab/cs-0) -```csharp - // Delete comments by a specific author. Pass an empty string for the - // author to delete all comments, by all authors. - public static void DeleteComments(string fileName, - string author = "") -``` - +[!code-csharp[](../../samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - ' Delete comments by a specific author. Pass an empty string for the author - ' to delete all comments, by all authors. - Public Sub DeleteComments(ByVal fileName As String, - Optional ByVal author As String = "") -``` +[!code-vb[](../../samples/word/delete_comments_by_all_or_a_specific_author/vb/Program.vb#snippet1)] *** @@ -59,73 +48,33 @@ an author name, the code deletes all comments. ## Calling the DeleteComments Method -To call the **DeleteComments** method, provide +To call the `DeleteComments` method, provide the required parameters as shown in the following code. ### [C#](#tab/cs-1) -```csharp - DeleteComments(@"C:\Users\Public\Documents\DeleteComments.docx", - "David Jones"); -``` - +[!code-csharp[](../../samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-1) -```vb - DeleteComments("C:\Users\Public\Documents\DeleteComments.docx", - "David Jones") -``` +[!code-vb[](../../samples/word/delete_comments_by_all_or_a_specific_author/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 comments part, using the [WordprocessingCommentsPart](/dotnet/api/documentformat.openxml.packaging.maindocumentpart.wordprocessingcommentspart) property of the -main document part, after having retrieved a reference to the main -document part from the [MainDocumentPart](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.maindocumentpart) property of the word -processing document. If the comments part is missing, there is no point + +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 comments +part, using the +property of the main document part, after having retrieved a reference to the main +document part from the +property of the word processing document. If the comments part is missing, there is no point in proceeding, as there cannot be any comments to delete. ### [C#](#tab/cs-2) -```csharp - // Get an existing Wordprocessing document. - using (WordprocessingDocument document = - WordprocessingDocument.Open(fileName, true)) - { - // Set commentPart to the document WordprocessingCommentsPart, - // if it exists. - WordprocessingCommentsPart commentPart = - document.MainDocumentPart.WordprocessingCommentsPart; - - // If no WordprocessingCommentsPart exists, there can be no - // comments. Stop execution and return from the method. - if (commentPart == null) - { - return; - } - // Code removed here… - } -``` - +[!code-csharp[](../../samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-2) -```vb - ' Get an existing Wordprocessing document. - Using document As WordprocessingDocument = - WordprocessingDocument.Open(fileName, True) - ' Set commentPart to the document - ' WordprocessingCommentsPart, if it exists. - Dim commentPart As WordprocessingCommentsPart = - document.MainDocumentPart.WordprocessingCommentsPart - - ' If no WordprocessingCommentsPart exists, there can be no - ' comments. Stop execution and return from the method. - If (commentPart Is Nothing) Then - Return - End If - ' Code removed here… - End Using -``` +[!code-vb[](../../samples/word/delete_comments_by_all_or_a_specific_author/vb/Program.vb#snippet3)] *** @@ -138,64 +87,40 @@ delete, and creating a list of comment IDs that correspond to the comments to delete. Given these lists, the code can both delete the comments from the comments part that contains the comments, and delete the references to the comments from the document part.The following code -starts by retrieving a list of [Comment](/dotnet/api/documentformat.openxml.wordprocessing.comment) elements. To retrieve the list, it -converts the [Elements](/dotnet/api/documentformat.openxml.openxmlelement.elements) collection exposed by the **commentPart** variable into a list of **Comment** objects. +starts by retrieving a list of +elements. To retrieve the list, it converts the +collection exposed by the `commentPart` variable into a list of `Comment` objects. ### [C#](#tab/cs-3) -```csharp - List commentsToDelete = - commentPart.Comments.Elements().ToList(); -``` - +[!code-csharp[](../../samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs#snippet4)] ### [Visual Basic](#tab/vb-3) -```vb - Dim commentsToDelete As List(Of Comment) = _ - commentPart.Comments.Elements(Of Comment)().ToList() -``` +[!code-vb[](../../samples/word/delete_comments_by_all_or_a_specific_author/vb/Program.vb#snippet4)] *** So far, the list of comments contains all of the comments. If the author parameter is not an empty string, the following code limits the list to -only those comments where the [Author](/dotnet/api/documentformat.openxml.wordprocessing.comment.author) property matches the parameter you -supplied. +only those comments where the +property matches the parameter you supplied. ### [C#](#tab/cs-4) -```csharp - if (!String.IsNullOrEmpty(author)) - { - commentsToDelete = commentsToDelete. - Where(c => c.Author == author).ToList(); - } -``` - +[!code-csharp[](../../samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs#snippet5)] ### [Visual Basic](#tab/vb-4) -```vb - If Not String.IsNullOrEmpty(author) Then - commentsToDelete = commentsToDelete. - Where(Function(c) c.Author = author).ToList() - End If -``` +[!code-vb[](../../samples/word/delete_comments_by_all_or_a_specific_author/vb/Program.vb#snippet5)] *** Before deleting any comments, the code retrieves a list of comments ID values, so that it can later delete matching elements from the document -part. The call to the [Select](/dotnet/api/system.linq.enumerable.select) -method effectively projects the list of comments, retrieving an [IEnumerable\](/dotnet/api/system.collections.generic.ienumerable-1) -of strings that contain all the comment ID values. +part. The call to the +method effectively projects the list of comments, retrieving an + of strings that +contain all the comment ID values. ### [C#](#tab/cs-5) -```csharp - IEnumerable commentIds = - commentsToDelete.Select(r => r.Id.Value); -``` - +[!code-csharp[](../../samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs#snippet6)] ### [Visual Basic](#tab/vb-5) -```vb - Dim commentIds As IEnumerable(Of String) = - commentsToDelete.Select(Function(r) r.Id.Value) -``` +[!code-vb[](../../samples/word/delete_comments_by_all_or_a_specific_author/vb/Program.vb#snippet6)] *** @@ -203,34 +128,14 @@ of strings that contain all the comment ID values. ## Deleting Comments and Saving the Part -Given the **commentsToDelete** collection, to +Given the `commentsToDelete` collection, to the following code loops through all the comments that require deleting and performs the deletion. The code then saves the comments part. ### [C#](#tab/cs-6) -```csharp - // Delete each comment in commentToDelete from the - // Comments collection. - foreach (Comment c in commentsToDelete) - { - c.Remove(); - } - - // Save the comment part changes. - commentPart.Comments.Save(); -``` - +[!code-csharp[](../../samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs#snippet7)] ### [Visual Basic](#tab/vb-6) -```vb - ' Delete each comment in commentToDelete from the Comments - ' collection. - For Each c As Comment In commentsToDelete - c.Remove() - Next - - ' Save the comment part changes. - commentPart.Comments.Save() -``` +[!code-vb[](../../samples/word/delete_comments_by_all_or_a_specific_author/vb/Program.vb#snippet7)] *** @@ -241,10 +146,13 @@ and performs the deletion. The code then saves the comments part. Although the code has successfully removed all the comments by this point, that is not enough. The code must also remove references to the comments from the document part. This action requires three steps -because the comment reference includes the [CommentRangeStart](/dotnet/api/documentformat.openxml.wordprocessing.commentrangestart), [CommentRangeEnd](/dotnet/api/documentformat.openxml.wordprocessing.commentrangeend), and [CommentReference](/dotnet/api/documentformat.openxml.wordprocessing.commentreference) elements, and the code -must remove all three for each comment. Before performing any deletions, -the code first retrieves a reference to the root element of the main -document part, as shown in the following code. +because the comment reference includes the +, +, +and +elements, and the code must remove all three for each comment. +Before performing any deletions, the code first retrieves a reference +to the root element of the main document part, as shown in the following code. ### [C#](#tab/cs-7) ```csharp @@ -261,76 +169,16 @@ document part, as shown in the following code. Given a reference to the document element, the following code performs its deletion loop three times, once for each of the different elements it must delete. In each case, the code looks for all descendants of the -correct type (**CommentRangeStart**, **CommentRangeEnd**, or **CommentReference**) and limits the list to those -whose [Id](/dotnet/api/documentformat.openxml.wordprocessing.markuprangetype.id) property value is contained in the list -of comment IDs to be deleted. Given the list of elements to be deleted, -the code removes each element in turn. Finally, the code completes by -saving the document. +correct type (`CommentRangeStart`, `CommentRangeEnd`, or `CommentReference`) +and limits the list to those whose +property value is contained in the list of comment IDs to be deleted. +Given the list of elements to be deleted, the code removes each element in turn. +Finally, the code completes by saving the document. ### [C#](#tab/cs-8) -```csharp - // Delete CommentRangeStart for each - // deleted comment in the main document. - List commentRangeStartToDelete = - doc.Descendants(). - Where(c => commentIds.Contains(c.Id.Value)).ToList(); - foreach (CommentRangeStart c in commentRangeStartToDelete) - { - c.Remove(); - } - - // Delete CommentRangeEnd for each deleted comment in the main document. - List commentRangeEndToDelete = - doc.Descendants(). - Where(c => commentIds.Contains(c.Id.Value)).ToList(); - foreach (CommentRangeEnd c in commentRangeEndToDelete) - { - c.Remove(); - } - - // Delete CommentReference for each deleted comment in the main document. - List commentRangeReferenceToDelete = - doc.Descendants(). - Where(c => commentIds.Contains(c.Id.Value)).ToList(); - foreach (CommentReference c in commentRangeReferenceToDelete) - { - c.Remove(); - } - - // Save changes back to the MainDocumentPart part. - doc.Save(); -``` - +[!code-csharp[](../../samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs#snippet9)] ### [Visual Basic](#tab/vb-8) -```vb - ' Delete CommentRangeStart for each - ' deleted comment in the main document. - Dim commentRangeStartToDelete As List(Of CommentRangeStart) = _ - doc.Descendants(Of CommentRangeStart). _ - Where(Function(c) commentIds.Contains(c.Id.Value)).ToList() - For Each c As CommentRangeStart In commentRangeStartToDelete - c.Remove() - Next - - ' Delete CommentRangeEnd for each deleted comment in the main document. - Dim commentRangeEndToDelete As List(Of CommentRangeEnd) = _ - doc.Descendants(Of CommentRangeEnd). _ - Where(Function(c) commentIds.Contains(c.Id.Value)).ToList() - For Each c As CommentRangeEnd In commentRangeEndToDelete - c.Remove() - Next - - ' Delete CommentReference for each deleted comment in the main document. - Dim commentRangeReferenceToDelete As List(Of CommentReference) = _ - doc.Descendants(Of CommentReference). _ - Where(Function(c) commentIds.Contains(c.Id.Value)).ToList - For Each c As CommentReference In commentRangeReferenceToDelete - c.Remove() - Next - - ' Save changes back to the MainDocumentPart part. - doc.Save() -``` +[!code-vb[](../../samples/word/delete_comments_by_all_or_a_specific_author/vb/Program.vb#snippet9)] *** @@ -341,10 +189,10 @@ saving the document. The following is the complete code sample in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs)] +[!code-csharp[](../../samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs#snippet)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/delete_comments_by_all_or_a_specific_author/vb/Program.vb)] +[!code-vb[](../../samples/word/delete_comments_by_all_or_a_specific_author/vb/Program.vb#snippet)] -------------------------------------------------------------------------------- diff --git a/samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs b/samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs index 80cbae92..320386d9 100644 --- a/samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs +++ b/samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs @@ -1,28 +1,30 @@ +// using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System; using System.Collections.Generic; using System.Linq; -DeleteComments(args[0], args[1]); +// // Delete comments by a specific author. Pass an empty string for the // author to delete all comments, by all authors. static void DeleteComments(string fileName, string author = "") +// { + // // Get an existing Wordprocessing document. using (WordprocessingDocument document = WordprocessingDocument.Open(fileName, true)) { - if (document.MainDocumentPart is null || document.MainDocumentPart.WordprocessingCommentsPart is null) + if (document.MainDocumentPart is null) { - throw new ArgumentNullException("MainDocumentPart and/or WordprocessingCommentsPart is null."); + throw new ArgumentNullException("MainDocumentPart is null."); } // Set commentPart to the document WordprocessingCommentsPart, // if it exists. - WordprocessingCommentsPart commentPart = - document.MainDocumentPart.WordprocessingCommentsPart; + WordprocessingCommentsPart? commentPart = document.MainDocumentPart.WordprocessingCommentsPart; // If no WordprocessingCommentsPart exists, there can be no // comments. Stop execution and return from the method. @@ -30,54 +32,71 @@ static void DeleteComments(string fileName, string author = "") { return; } + // // Create a list of comments by the specified author, or // if the author name is empty, all authors. - List commentsToDelete = - commentPart.Comments.Elements().ToList(); + // + List commentsToDelete = commentPart.Comments.Elements().ToList(); + // + + // if (!String.IsNullOrEmpty(author)) { - commentsToDelete = commentsToDelete. - Where(c => c.Author == author).ToList(); + commentsToDelete = commentsToDelete.Where(c => c.Author == author).ToList(); } - IEnumerable commentIds = - commentsToDelete.Where(r => r.Id is not null && r.Id.HasValue).Select(r => r.Id?.Value); + // + + // + IEnumerable commentIds = commentsToDelete.Where(r => r.Id is not null && r.Id.HasValue).Select(r => r.Id?.Value); + // + // // Delete each comment in commentToDelete from the // Comments collection. foreach (Comment c in commentsToDelete) { - c.Remove(); + if (c is not null) + { + c.Remove(); + } } // Save the comment part change. commentPart.Comments.Save(); + // + // Document doc = document.MainDocumentPart.Document; + // + // // Delete CommentRangeStart for each // deleted comment in the main document. - List commentRangeStartToDelete = - doc.Descendants(). - Where(c => c.Id is not null && c.Id.HasValue && commentIds.Contains(c.Id.Value)).ToList(); + List commentRangeStartToDelete = doc.Descendants() + .Where(c => c.Id is not null && c.Id.HasValue && commentIds.Contains(c.Id.Value)) + .ToList(); + foreach (CommentRangeStart c in commentRangeStartToDelete) { c.Remove(); } // Delete CommentRangeEnd for each deleted comment in the main document. - List commentRangeEndToDelete = - doc.Descendants(). - Where(c => c.Id is not null && c.Id.HasValue && commentIds.Contains(c.Id.Value)).ToList(); + List commentRangeEndToDelete = doc.Descendants() + .Where(c => c.Id is not null && c.Id.HasValue && commentIds.Contains(c.Id.Value)) + .ToList(); + foreach (CommentRangeEnd c in commentRangeEndToDelete) { c.Remove(); } // Delete CommentReference for each deleted comment in the main document. - List commentRangeReferenceToDelete = - doc.Descendants(). - Where(c => c.Id is not null && c.Id.HasValue && commentIds.Contains(c.Id.Value)).ToList(); + List commentRangeReferenceToDelete = doc.Descendants() + .Where(c => c.Id is not null && c.Id.HasValue && commentIds.Contains(c.Id.Value)) + .ToList(); + foreach (CommentReference c in commentRangeReferenceToDelete) { c.Remove(); @@ -85,5 +104,18 @@ static void DeleteComments(string fileName, string author = "") // Save changes back to the MainDocumentPart part. doc.Save(); + // } -} \ No newline at end of file +} +// + +// +if (args is [{ } fileName, { } author]) +{ + DeleteComments(fileName, author); +} +else if (args is [{ } fileName2]) +{ + DeleteComments(fileName2); +} +// diff --git a/samples/word/delete_comments_by_all_or_a_specific_author/vb/Program.vb b/samples/word/delete_comments_by_all_or_a_specific_author/vb/Program.vb index 59deeb07..5e7cc1fd 100644 --- a/samples/word/delete_comments_by_all_or_a_specific_author/vb/Program.vb +++ b/samples/word/delete_comments_by_all_or_a_specific_author/vb/Program.vb @@ -1,79 +1,110 @@ +' Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Wordprocessing Module Program Sub Main(args As String()) + ' + If (args.Length >= 2) Then + Dim fileName As String = args(0) + Dim author As String = args(1) + + DeleteComments(fileName, author) + ElseIf args.Length = 1 Then + Dim fileName As String = args(0) + + DeleteComments(fileName) + End If + ' End Sub + ' ' Delete comments by a specific author. Pass an empty string for the author ' to delete all comments, by all authors. - Public Sub DeleteComments(ByVal fileName As String, - Optional ByVal author As String = "") + Public Sub DeleteComments(ByVal fileName As String, Optional ByVal author As String = "") + ' + ' ' Get an existing Wordprocessing document. - Using document As WordprocessingDocument = - WordprocessingDocument.Open(fileName, True) + Using document As WordprocessingDocument = WordprocessingDocument.Open(fileName, True) ' Set commentPart to the document ' WordprocessingCommentsPart, if it exists. - Dim commentPart As WordprocessingCommentsPart = - document.MainDocumentPart.WordprocessingCommentsPart + Dim commentPart As WordprocessingCommentsPart = document.MainDocumentPart.WordprocessingCommentsPart ' If no WordprocessingCommentsPart exists, there can be no ' comments. Stop execution and return from the method. If (commentPart Is Nothing) Then Return End If + ' ' Create a list of comments by the specified author, or ' if the author name is empty, all authors. - Dim commentsToDelete As List(Of Comment) = - commentPart.Comments.Elements(Of Comment)().ToList() + ' + Dim commentsToDelete As List(Of Comment) = commentPart.Comments.Elements(Of Comment)().ToList() + ' + + ' If Not String.IsNullOrEmpty(author) Then - commentsToDelete = commentsToDelete. - Where(Function(c) c.Author = author).ToList() + commentsToDelete = commentsToDelete.Where(Function(c) c.Author = author).ToList() End If - Dim commentIds As IEnumerable(Of String) = - commentsToDelete.Select(Function(r) r.Id.Value) + ' + + ' + Dim commentIds As IEnumerable(Of String) = commentsToDelete.Where(Function(r) r IsNot Nothing And r.Id.HasValue).Select(Function(r) r.Id.Value) + ' + ' ' Delete each comment in commentToDelete from the Comments ' collection. For Each c As Comment In commentsToDelete - c.Remove() + If (c IsNot Nothing) Then + c.Remove() + End If Next ' Save the comment part change. commentPart.Comments.Save() + ' + ' Dim doc As Document = document.MainDocumentPart.Document + ' + ' ' Delete CommentRangeStart for each ' deleted comment in the main document. - Dim commentRangeStartToDelete As List(Of CommentRangeStart) = - doc.Descendants(Of CommentRangeStart). - Where(Function(c) commentIds.Contains(c.Id.Value)).ToList() + Dim commentRangeStartToDelete As List(Of CommentRangeStart) = doc.Descendants(Of CommentRangeStart). + Where(Function(c) commentIds.Contains(c.Id.Value)). + ToList() + For Each c As CommentRangeStart In commentRangeStartToDelete c.Remove() Next ' Delete CommentRangeEnd for each deleted comment in main document. - Dim commentRangeEndToDelete As List(Of CommentRangeEnd) = - doc.Descendants(Of CommentRangeEnd). - Where(Function(c) commentIds.Contains(c.Id.Value)).ToList() + Dim commentRangeEndToDelete As List(Of CommentRangeEnd) = doc.Descendants(Of CommentRangeEnd). + Where(Function(c) commentIds.Contains(c.Id.Value)). + ToList() + For Each c As CommentRangeEnd In commentRangeEndToDelete c.Remove() Next ' Delete CommentReference for each deleted comment in the main document. - Dim commentRangeReferenceToDelete As List(Of CommentReference) = - doc.Descendants(Of CommentReference). - Where(Function(c) commentIds.Contains(c.Id.Value)).ToList + Dim commentRangeReferenceToDelete As List(Of CommentReference) = doc.Descendants(Of CommentReference). + Where(Function(c) commentIds.Contains(c.Id.Value)). + ToList() + For Each c As CommentReference In commentRangeReferenceToDelete c.Remove() Next ' Save changes back to the MainDocumentPart part. doc.Save() + ' End Using End Sub -End Module \ No newline at end of file +End Module +' From a37abb3ff173f26b758a454b5f0e7145b28d229b Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Tue, 13 Feb 2024 10:59:36 -0800 Subject: [PATCH 013/103] closes #213 --- ...aph-style-to-a-word-processing-document.md | 347 ++---------------- .../cs/Program.cs | 210 +++++++---- .../vb/Program.vb | 71 +++- 3 files changed, 250 insertions(+), 378 deletions(-) diff --git a/docs/word/how-to-create-and-add-a-paragraph-style-to-a-word-processing-document.md b/docs/word/how-to-create-and-add-a-paragraph-style-to-a-word-processing-document.md index 1ec0f0f8..6d541628 100644 --- a/docs/word/how-to-create-and-add-a-paragraph-style-to-a-word-processing-document.md +++ b/docs/word/how-to-create-and-add-a-paragraph-style-to-a-word-processing-document.md @@ -12,7 +12,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 06/28/2021 +ms.date: 02/13/2024 ms.localizationpriority: high --- # Create and add a paragraph style to a word processing 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 create and add a paragraph style to a word processing document. It contains an example -**CreateAndAddParagraphStyle** method to illustrate this task, plus a +`CreateAndAddParagraphStyle` method to illustrate this task, plus a supplemental example method to add the styles part when necessary. @@ -29,7 +29,7 @@ supplemental example method to add the styles part when necessary. ## CreateAndAddParagraphStyle Method -The **CreateAndAddParagraphStyle** sample method can be used to add a +The `CreateAndAddParagraphStyle` sample method can be used to add a style to a word processing document. You must first obtain a reference to the style definitions part in the document to which you want to add the style. For more information and an example of how to do this, see @@ -43,16 +43,9 @@ interface), and optionally, any style aliases (alternate names for use in the user interface). ### [C#](#tab/cs-0) -```csharp - public static void CreateAndAddParagraphStyle(StyleDefinitionsPart styleDefinitionsPart, - string styleid, string stylename, string aliases="") -``` - +[!code-csharp[](../../samples/word/create_and_add_a_paragraph_style/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - Public Sub CreateAndAddParagraphStyle(ByVal styleDefinitionsPart As StyleDefinitionsPart, - ByVal styleid As String, ByVal stylename As String, Optional ByVal aliases As String = "") -``` +[!code-vb[](../../samples/word/create_and_add_a_paragraph_style/vb/Program.vb#snippet1)] *** @@ -75,7 +68,7 @@ For example, consider the following XML code example taken from a style definition. ```xml - . . . @@ -94,125 +87,23 @@ application. ## Calling the Sample Method -Use the **CreateAndAddParagraphStyle** example +Use the `CreateAndAddParagraphStyle` example method to create and add a named style to a word processing document using the Open XML SDK. The following code example shows how to open and obtain a reference to a word processing document, retrieve a reference -to the style definitions part of the document, and then call the **CreateAndAddParagraphStyle** method. +to the style definitions part of the document, and then call the `CreateAndAddParagraphStyle` method. To call the method, pass a reference to the style definitions part as the first parameter, the style ID of the style as the second parameter, the name of the style as the third parameter, and optionally, any style aliases as the fourth parameter. For example, the following code creates -the "Overdue Amount Para" paragraph style in a sample file that is named -CreateAndAddParagraphStyle.docx. It also adds a paragraph of text, and +the "Overdue Amount Para" paragraph style. It also adds a paragraph of text, and applies the style to the paragraph. ### [C#](#tab/cs-1) -```csharp - string strDoc = @"C:\Users\Public\Documents\CreateAndAddParagraphStyle.docx"; - - using (WordprocessingDocument doc = - WordprocessingDocument.Open(strDoc, true)) - { - // 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); - } - - // Set up a variable to hold the style ID. - string parastyleid = "OverdueAmountPara"; - - // Create and add a paragraph style to the specified styles part - // with the specified style ID, style name and aliases. - CreateAndAddParagraphStyle(part, - parastyleid, - "Overdue Amount Para", - "Late Due, Late Amount"); - - // Add a paragraph with a run and some text. - Paragraph p = - new Paragraph( - new Run( - new Text("This is some text in a run in a paragraph."))); - - // Add the paragraph as a child element of the w:body element. - doc.MainDocumentPart.Document.Body.AppendChild(p); - - // If the paragraph has no ParagraphProperties object, create one. - if (p.Elements().Count() == 0) - { - p.PrependChild(new ParagraphProperties()); - } - - // Get a reference to the ParagraphProperties object. - ParagraphProperties pPr = p.ParagraphProperties; - - // If a ParagraphStyleId object doesn't exist, create one. - if (pPr.ParagraphStyleId == null) - pPr.ParagraphStyleId = new ParagraphStyleId(); - - // Set the style of the paragraph. - pPr.ParagraphStyleId.Val = parastyleid; - } -``` - +[!code-csharp[](../../samples/word/create_and_add_a_paragraph_style/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-1) -```vb - Dim strDoc As String = "C:\Users\Public\Documents\CreateAndAddParagraphStyle.docx" - - Using doc As WordprocessingDocument = - WordprocessingDocument.Open(strDoc, True) - - ' Get the Styles part for this document. - Dim part As StyleDefinitionsPart = - doc.MainDocumentPart.StyleDefinitionsPart - - ' If the Styles part does not exist, add it. - If part Is Nothing Then - part = AddStylesPartToPackage(doc) - End If - - ' Set up a variable to hold the style ID. - Dim parastyleid As String = "OverdueAmountPara" - - ' Create and add a paragraph style to the specified styles part - ' with the specified style ID, style name and aliases. - CreateAndAddParagraphStyle(part, - parastyleid, - "Overdue Amount Para", - "Late Due, Late Amount") - - ' Add a paragraph with a run and some text. - Dim p As New Paragraph( - New Run( - New Text("This is some text in a run in a paragraph."))) - - ' Add the paragraph as a child element of the w:body element. - doc.MainDocumentPart.Document.Body.AppendChild(p) - - ' 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 a reference to the ParagraphProperties object. - Dim pPr As ParagraphProperties = p.ParagraphProperties - - ' If a ParagraphStyleId object doesn't exist, create one. - If pPr.ParagraphStyleId Is Nothing Then - pPr.ParagraphStyleId = New ParagraphStyleId() - End If - - ' Set the style of the paragraph. - pPr.ParagraphStyleId.Val = parastyleid - End Using -``` +[!code-vb[](../../samples/word/create_and_add_a_paragraph_style/vb/Program.vb#snippet2)] *** @@ -315,32 +206,16 @@ styleId attribute value for this style in the paragraph properties' ## How the Code Works -The **CreateAndAddParagraphStyle** method +The `CreateAndAddParagraphStyle` method begins by retrieving a reference to the styles element in the styles part. The styles element is the root element of the part and contains all of the individual style elements. If the reference is null, the styles element is created and saved to the part. ### [C#](#tab/cs-2) -```csharp - // Access the root element of the styles part. - Styles styles = styleDefinitionsPart.Styles; - if (styles == null) - { - styleDefinitionsPart.Styles = new Styles(); - styleDefinitionsPart.Styles.Save(); - } -``` - +[!code-csharp[](../../samples/word/create_and_add_a_paragraph_style/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-2) -```vb - ' Access the root element of the styles part. - Dim styles As Styles = styleDefinitionsPart.Styles - If styles Is Nothing Then - styleDefinitionsPart.Styles = New Styles() - styleDefinitionsPart.Styles.Save() - End If -``` +[!code-vb[](../../samples/word/create_and_add_a_paragraph_style/vb/Program.vb#snippet3)] *** @@ -348,28 +223,16 @@ styles element is created and saved to the part. ## Creating the Style -To create the style, the code instantiates the **[Style](/dotnet/api/documentformat.openxml.wordprocessing.style)** class and sets certain properties, -such as the **[Type](/dotnet/api/documentformat.openxml.wordprocessing.style.type)** of style (paragraph), the **[StyleId](/dotnet/api/documentformat.openxml.wordprocessing.style.styleid)**, whether the style is a **[CustomStyle](/dotnet/api/documentformat.openxml.wordprocessing.style.customstyle)**, and whether the style is the -**[Default](/dotnet/api/documentformat.openxml.wordprocessing.style.default)** style for its type. +To create the style, the code instantiates the +class and sets certain properties, such as the +of style (paragraph), the , whether the +style is a , and whether the style is the + style for its type. ### [C#](#tab/cs-3) -```csharp - // Create a new paragraph style element and specify some of the attributes. - Style style = new Style() { Type = StyleValues.Paragraph, - StyleId = styleid, - CustomStyle = true, - Default = false - }; -``` - +[!code-csharp[](../../samples/word/create_and_add_a_paragraph_style/cs/Program.cs#snippet4)] ### [Visual Basic](#tab/vb-3) -```vb - ' Create a new paragraph style element and specify some of the attributes. - Dim style As New Style() With { .Type = StyleValues.Paragraph, _ - .StyleId = styleid, _ - .CustomStyle = True, _ - .[Default] = False} -``` +[!code-vb[](../../samples/word/create_and_add_a_paragraph_style/vb/Program.vb#snippet4)] *** @@ -384,128 +247,29 @@ The code results in the following XML. The code next creates the child elements of the style, which define the properties of the style. To create an element, you instantiate its -corresponding class, and then call the **[Append([])](/dotnet/api/documentformat.openxml.openxmlelement.append)** method add the child element to -the style. For more information about these properties, see section 17.7 -of the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] +corresponding class, and then call the +method add the child element to the style. For more information about these properties, +see section 17.7 of the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification. ### [C#](#tab/cs-4) -```csharp - // Create and add the child elements (properties of the style). - Aliases aliases1 = new Aliases() { Val = aliases }; - AutoRedefine autoredefine1 = new AutoRedefine() { Val = OnOffOnlyValues.Off }; - BasedOn basedon1 = new BasedOn() { Val = "Normal" }; - LinkedStyle linkedStyle1 = new LinkedStyle() { Val = "OverdueAmountChar" }; - Locked locked1 = new Locked() { Val = OnOffOnlyValues.Off }; - PrimaryStyle primarystyle1 = new PrimaryStyle() { Val = OnOffOnlyValues.On }; - StyleHidden stylehidden1 = new StyleHidden() { Val = OnOffOnlyValues.Off }; - SemiHidden semihidden1 = new SemiHidden() { Val = OnOffOnlyValues.Off }; - StyleName styleName1 = new StyleName() { Val = stylename }; - NextParagraphStyle nextParagraphStyle1 = new NextParagraphStyle() { Val = "Normal" }; - UIPriority uipriority1 = new UIPriority() { Val = 1 }; - UnhideWhenUsed unhidewhenused1 = new UnhideWhenUsed() { Val = OnOffOnlyValues.On }; - if (aliases != "") - style.Append(aliases1); - style.Append(autoredefine1); - style.Append(basedon1); - style.Append(linkedStyle1); - style.Append(locked1); - style.Append(primarystyle1); - style.Append(stylehidden1); - style.Append(semihidden1); - style.Append(styleName1); - style.Append(nextParagraphStyle1); - style.Append(uipriority1); - style.Append(unhidewhenused1); -``` - +[!code-csharp[](../../samples/word/create_and_add_a_paragraph_style/cs/Program.cs#snippet5)] ### [Visual Basic](#tab/vb-4) -```vb - ' Create and add the child elements (properties of the style) - Dim aliases1 As New Aliases() With {.Val = aliases} - Dim autoredefine1 As New AutoRedefine() With {.Val = OnOffOnlyValues.Off} - Dim basedon1 As New BasedOn() With {.Val = "Normal"} - Dim linkedStyle1 As New LinkedStyle() With {.Val = "OverdueAmountChar"} - Dim locked1 As New Locked() With {.Val = OnOffOnlyValues.Off} - Dim primarystyle1 As New PrimaryStyle() With {.Val = OnOffOnlyValues.[On]} - Dim stylehidden1 As New StyleHidden() With {.Val = OnOffOnlyValues.Off} - Dim semihidden1 As New SemiHidden() With {.Val = OnOffOnlyValues.Off} - Dim styleName1 As New StyleName() With {.Val = stylename} - Dim nextParagraphStyle1 As New NextParagraphStyle() With { _ - .Val = "Normal"} - Dim uipriority1 As New UIPriority() With {.Val = 1} - Dim unhidewhenused1 As New UnhideWhenUsed() With { _ - .Val = OnOffOnlyValues.[On]} - If aliases <> "" Then - style.Append(aliases1) - End If - style.Append(autoredefine1) - style.Append(basedon1) - style.Append(linkedStyle1) - style.Append(locked1) - style.Append(primarystyle1) - style.Append(stylehidden1) - style.Append(semihidden1) - style.Append(styleName1) - style.Append(nextParagraphStyle1) - style.Append(uipriority1) - style.Append(unhidewhenused1) -``` +[!code-vb[](../../samples/word/create_and_add_a_paragraph_style/vb/Program.vb#snippet5)] *** -Next, the code instantiates a **[StyleRunProperties](/dotnet/api/documentformat.openxml.wordprocessing.stylerunproperties)** object to create a **rPr** (Run Properties) element. You specify the character properties that apply to the style, such as font and color, in this element. The properties are then appended as children of the **rPr** element. +Next, the code instantiates a +object to create a `rPr` (Run Properties) element. You specify the character properties that +apply to the style, such as font and color, in this element. The properties are then appended +as children of the `rPr` element. -When the run properties are created, the code appends the **rPr** element to the style, and the style element to the styles root element in the styles part. +When the run properties are created, the code appends the `rPr` element to the style, and the style element to the styles root element in the styles part. ### [C#](#tab/cs-5) -```csharp - // Create the StyleRunProperties object and specify some of the run properties. - StyleRunProperties styleRunProperties1 = new StyleRunProperties(); - Bold bold1 = new Bold(); - Color color1 = new Color() { ThemeColor = ThemeColorValues.Accent2 }; - RunFonts font1 = new RunFonts() { Ascii = "Lucida Console" }; - Italic italic1 = new Italic(); - // Specify a 12 point size. - FontSize fontSize1 = new FontSize() { Val = "24" }; - styleRunProperties1.Append(bold1); - styleRunProperties1.Append(color1); - styleRunProperties1.Append(font1); - styleRunProperties1.Append(fontSize1); - styleRunProperties1.Append(italic1); - - // Add the run properties to the style. - style.Append(styleRunProperties1); - - // Add the style to the styles part. - styles.Append(style); -``` - +[!code-csharp[](../../samples/word/create_and_add_a_paragraph_style/cs/Program.cs#snippet6)] ### [Visual Basic](#tab/vb-5) -```vb - ' Create the StyleRunProperties object and specify some of the run properties. - Dim styleRunProperties1 As New StyleRunProperties() - Dim bold1 As New Bold() - Dim color1 As New Color() With { _ - .ThemeColor = ThemeColorValues.Accent2} - Dim font1 As New RunFonts() With { _ - .Ascii = "Lucida Console"} - Dim italic1 As New Italic() - ' Specify a 12 point size. - Dim fontSize1 As New FontSize() With { _ - .Val = "24"} - styleRunProperties1.Append(bold1) - styleRunProperties1.Append(color1) - styleRunProperties1.Append(font1) - styleRunProperties1.Append(fontSize1) - styleRunProperties1.Append(italic1) - - ' Add the run properties to the style. - style.Append(styleRunProperties1) - - ' Add the style to the styles part. - styles.Append(style) -``` +[!code-vb[](../../samples/word/create_and_add_a_paragraph_style/vb/Program.vb#snippet6)] *** @@ -518,45 +282,12 @@ referencing the styleId attribute value for this style in the paragraph properties' pStyle element. The following code example shows how to apply a style to a paragraph referenced by the variable p. The style ID of the style to apply is stored in the parastyleid variable, and the -ParagraphStyleId property represents the paragraph properties' **pStyle** element. +ParagraphStyleId property represents the paragraph properties' `pStyle` element. ### [C#](#tab/cs-6) -```csharp - // If the paragraph has no ParagraphProperties object, create one. - if (p.Elements().Count() == 0) - { - p.PrependChild(new ParagraphProperties()); - } - - // Get a reference to the ParagraphProperties object. - ParagraphProperties pPr = p.ParagraphProperties; - - // If a ParagraphStyleId object does not exist, create one. - if (pPr.ParagraphStyleId == null) - pPr.ParagraphStyleId = new ParagraphStyleId(); - - // Set the style of the paragraph. - pPr.ParagraphStyleId.Val = parastyleid; -``` - +[!code-csharp[](../../samples/word/create_and_add_a_paragraph_style/cs/Program.cs#snippet7)] ### [Visual Basic](#tab/vb-6) -```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 a reference to the ParagraphProperties object. - Dim pPr As ParagraphProperties = p.ParagraphProperties - - ' If a ParagraphStyleId object does not exist, create one. - If pPr.ParagraphStyleId Is Nothing Then - pPr.ParagraphStyleId = New ParagraphStyleId() - End If - - ' Set the style of the paragraph. - pPr.ParagraphStyleId.Val = parastyleid -``` +[!code-vb[](../../samples/word/create_and_add_a_paragraph_style/vb/Program.vb#snippet7)] *** @@ -564,14 +295,14 @@ ParagraphStyleId property represents the paragraph properties' **pStyle** elemen ## Sample Code -The following is the complete **CreateAndAddParagraphStyle** code sample in both +The following is the complete `CreateAndAddParagraphStyle` code sample in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/create_and_add_a_paragraph_style/cs/Program.cs)] +[!code-csharp[](../../samples/word/create_and_add_a_paragraph_style/cs/Program.cs#snippet)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/create_and_add_a_paragraph_style/vb/Program.vb)] +[!code-vb[](../../samples/word/create_and_add_a_paragraph_style/vb/Program.vb#snippet)] --------------------------------------------------------------------------------- diff --git a/samples/word/create_and_add_a_paragraph_style/cs/Program.cs b/samples/word/create_and_add_a_paragraph_style/cs/Program.cs index 2d605ff1..1b0fc280 100644 --- a/samples/word/create_and_add_a_paragraph_style/cs/Program.cs +++ b/samples/word/create_and_add_a_paragraph_style/cs/Program.cs @@ -1,78 +1,95 @@ +// using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System; +using System.Linq; -CreateAndAddParagraphStyle(args[0], args[1], args[2], args[3]); // Create a new paragraph style with the specified style ID, primary style name, and aliases and // add it to the specified style definitions part. -static void CreateAndAddParagraphStyle(string filePath, string styleid, string stylename, string aliases = "") +// +static void CreateAndAddParagraphStyle(StyleDefinitionsPart styleDefinitionsPart, string styleid, string stylename, string aliases = "") +// { - using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filePath, true)) + // + // Access the root element of the styles part. + Styles? styles = styleDefinitionsPart.Styles; + + if (styles is null) { - // Access the root element of the styles part. - Styles? styles = wordprocessingDocument?.MainDocumentPart?.StyleDefinitionsPart?.Styles ?? AddStylesPartToPackage(wordprocessingDocument).Styles; - - if (styles is not null) - { - - // Create a new paragraph style element and specify some of the attributes. - Style style = new Style() - { - Type = StyleValues.Paragraph, - StyleId = styleid, - CustomStyle = true, - Default = false - }; - - // Create and add the child elements (properties of the style). - Aliases aliases1 = new Aliases() { Val = aliases }; - AutoRedefine autoredefine1 = new AutoRedefine() { Val = OnOffOnlyValues.Off }; - BasedOn basedon1 = new BasedOn() { Val = "Normal" }; - LinkedStyle linkedStyle1 = new LinkedStyle() { Val = "OverdueAmountChar" }; - Locked locked1 = new Locked() { Val = OnOffOnlyValues.Off }; - PrimaryStyle primarystyle1 = new PrimaryStyle() { Val = OnOffOnlyValues.On }; - StyleHidden stylehidden1 = new StyleHidden() { Val = OnOffOnlyValues.Off }; - SemiHidden semihidden1 = new SemiHidden() { Val = OnOffOnlyValues.Off }; - StyleName styleName1 = new StyleName() { Val = stylename }; - NextParagraphStyle nextParagraphStyle1 = new NextParagraphStyle() { Val = "Normal" }; - UIPriority uipriority1 = new UIPriority() { Val = 1 }; - UnhideWhenUsed unhidewhenused1 = new UnhideWhenUsed() { Val = OnOffOnlyValues.On }; - if (aliases != "") - style.Append(aliases1); - style.Append(autoredefine1); - style.Append(basedon1); - style.Append(linkedStyle1); - style.Append(locked1); - style.Append(primarystyle1); - style.Append(stylehidden1); - style.Append(semihidden1); - style.Append(styleName1); - style.Append(nextParagraphStyle1); - style.Append(uipriority1); - style.Append(unhidewhenused1); - - // Create the StyleRunProperties object and specify some of the run properties. - StyleRunProperties styleRunProperties1 = new StyleRunProperties(); - Bold bold1 = new Bold(); - Color color1 = new Color() { ThemeColor = ThemeColorValues.Accent2 }; - RunFonts font1 = new RunFonts() { Ascii = "Lucida Console" }; - Italic italic1 = new Italic(); - // Specify a 12 point size. - FontSize fontSize1 = new FontSize() { Val = "24" }; - styleRunProperties1.Append(bold1); - styleRunProperties1.Append(color1); - styleRunProperties1.Append(font1); - styleRunProperties1.Append(fontSize1); - styleRunProperties1.Append(italic1); - - // Add the run properties to the style. - style.Append(styleRunProperties1); - - // Add the style to the styles part. - styles.Append(style); - } + styleDefinitionsPart.Styles = new Styles(); + styles = styleDefinitionsPart.Styles; + + styleDefinitionsPart.Styles.Save(); } + // + + // + // Create a new paragraph style element and specify some of the attributes. + Style style = new Style() + { + Type = StyleValues.Paragraph, + StyleId = styleid, + CustomStyle = true, + Default = false + }; + // + + // + // Create and add the child elements (properties of the style). + Aliases aliases1 = new Aliases() { Val = aliases }; + AutoRedefine autoredefine1 = new AutoRedefine() { Val = OnOffOnlyValues.Off }; + BasedOn basedon1 = new BasedOn() { Val = "Normal" }; + LinkedStyle linkedStyle1 = new LinkedStyle() { Val = "OverdueAmountChar" }; + Locked locked1 = new Locked() { Val = OnOffOnlyValues.Off }; + PrimaryStyle primarystyle1 = new PrimaryStyle() { Val = OnOffOnlyValues.On }; + StyleHidden stylehidden1 = new StyleHidden() { Val = OnOffOnlyValues.Off }; + SemiHidden semihidden1 = new SemiHidden() { Val = OnOffOnlyValues.Off }; + StyleName styleName1 = new StyleName() { Val = stylename }; + NextParagraphStyle nextParagraphStyle1 = new NextParagraphStyle() { Val = "Normal" }; + UIPriority uipriority1 = new UIPriority() { Val = 1 }; + UnhideWhenUsed unhidewhenused1 = new UnhideWhenUsed() { Val = OnOffOnlyValues.On }; + + if (string.IsNullOrWhiteSpace(aliases)) + { + style.Append(aliases1); + } + + style.Append(autoredefine1); + style.Append(basedon1); + style.Append(linkedStyle1); + style.Append(locked1); + style.Append(primarystyle1); + style.Append(stylehidden1); + style.Append(semihidden1); + style.Append(styleName1); + style.Append(nextParagraphStyle1); + style.Append(uipriority1); + style.Append(unhidewhenused1); + // + + // + // Create the StyleRunProperties object and specify some of the run properties. + StyleRunProperties styleRunProperties1 = new StyleRunProperties(); + Bold bold1 = new Bold(); + Color color1 = new Color() { ThemeColor = ThemeColorValues.Accent2 }; + RunFonts font1 = new RunFonts() { Ascii = "Lucida Console" }; + Italic italic1 = new Italic(); + + // Specify a 12 point size. + FontSize fontSize1 = new FontSize() { Val = "24" }; + styleRunProperties1.Append(bold1); + styleRunProperties1.Append(color1); + styleRunProperties1.Append(font1); + styleRunProperties1.Append(fontSize1); + styleRunProperties1.Append(italic1); + + // Add the run properties to the style. + style.Append(styleRunProperties1); + + // Add the style to the styles part. + styles.Append(style); + // } // Add a StylesDefinitionsPart to the document. Returns a reference to it. @@ -89,4 +106,65 @@ static StyleDefinitionsPart AddStylesPartToPackage(WordprocessingDocument? doc) Styles root = new Styles(); root.Save(part); return part; -} \ No newline at end of file +} + +// +string strDoc = args[0]; + +using (WordprocessingDocument doc = WordprocessingDocument.Open(strDoc, true)) +{ + if (doc is null) + { + throw new ArgumentNullException("document could not be opened"); + } + + MainDocumentPart mainDocumentPart = doc.MainDocumentPart ?? doc.AddMainDocumentPart(); + + // Get the Styles part for this document. + StyleDefinitionsPart? part = mainDocumentPart.StyleDefinitionsPart; + + // If the Styles part does not exist, add it and then add the style. + if (part is null) + { + part = AddStylesPartToPackage(doc); + } + + // Set up a variable to hold the style ID. + string parastyleid = "OverdueAmountPara"; + + // Create and add a paragraph style to the specified styles part + // with the specified style ID, style name and aliases. + CreateAndAddParagraphStyle(part, parastyleid, "Overdue Amount Para", "Late Due, Late Amount"); + + // Add a paragraph with a run and some text. + Paragraph p = + new Paragraph( + new Run( + new Text("This is some text in a run in a paragraph."))); + + // Add the paragraph as a child element of the w:body element. + mainDocumentPart.Document ??= new Document(); + mainDocumentPart.Document.Body ??= new Body(); + + mainDocumentPart.Document.Body.AppendChild(p); + + // + // If the paragraph has no ParagraphProperties object, create one. + if (p.Elements().Count() == 0) + { + p.PrependChild(new ParagraphProperties()); + } + + // Get a reference to the ParagraphProperties object. + p.ParagraphProperties ??= new ParagraphProperties(); + ParagraphProperties pPr = p.ParagraphProperties; + + // If a ParagraphStyleId object doesn't exist, create one. + pPr.ParagraphStyleId ??= new ParagraphStyleId(); + + // Set the style of the paragraph. + pPr.ParagraphStyleId.Val = parastyleid; + // +} +// +// diff --git a/samples/word/create_and_add_a_paragraph_style/vb/Program.vb b/samples/word/create_and_add_a_paragraph_style/vb/Program.vb index 5c0ba268..dc0cb1f8 100644 --- a/samples/word/create_and_add_a_paragraph_style/vb/Program.vb +++ b/samples/word/create_and_add_a_paragraph_style/vb/Program.vb @@ -1,30 +1,86 @@ +' Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Wordprocessing Module Program Sub Main(args As String()) + ' + Dim filePath As String = args(0) + + Using wordprocessingDocument As WordprocessingDocument = WordprocessingDocument.Open(args(0), True) + + ' Get the Styles part for this document. + Dim part As StyleDefinitionsPart = wordprocessingDocument.MainDocumentPart.StyleDefinitionsPart + + ' If the Styles part does not exist, add it. + If part Is Nothing Then + part = AddStylesPartToPackage(wordprocessingDocument) + End If + + ' Set up a variable to hold the style ID. + Dim parastyleid As String = "OverdueAmountPara" + + ' Create and add a paragraph style to the specified styles part + ' with the specified style ID, style name and aliases. + CreateAndAddParagraphStyle(part, parastyleid, "Overdue Amount Para", "Late Due, Late Amount") + + ' Add a paragraph with a run and some text. + Dim p As New Paragraph(New Run(New Text("This is some text in a run in a paragraph."))) + + ' Add the paragraph as a child element of the w:body element. + wordprocessingDocument.MainDocumentPart.Document.Body.AppendChild(p) + + ' + ' 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 a reference to the ParagraphProperties object. + Dim pPr As ParagraphProperties = p.ParagraphProperties + + ' If a ParagraphStyleId object doesn't exist, create one. + If pPr.ParagraphStyleId Is Nothing Then + pPr.ParagraphStyleId = New ParagraphStyleId() + End If + + ' Set the style of the paragraph. + pPr.ParagraphStyleId.Val = parastyleid + ' + End Using + ' End Sub ' Create a new paragraph style with the specified style ID, primary style name, and aliases and ' add it to the specified style definitions part. - Public Sub CreateAndAddParagraphStyle(ByVal styleDefinitionsPart As StyleDefinitionsPart, - ByVal styleid As String, ByVal stylename As String, Optional ByVal aliases As String = "") + ' + Public Sub CreateAndAddParagraphStyle(ByVal styleDefinitionsPart As StyleDefinitionsPart, ByVal styleid As String, ByVal stylename As String, Optional ByVal aliases As String = "") + ' + + ' ' Access the root element of the styles part. Dim styles As Styles = styleDefinitionsPart.Styles + If styles Is Nothing Then styleDefinitionsPart.Styles = New Styles() styleDefinitionsPart.Styles.Save() + + styles = styleDefinitionsPart.Styles End If + ' + ' ' Create a new paragraph style element and specify some of the attributes. Dim style As New Style() With { .Type = StyleValues.Paragraph, .StyleId = styleid, .CustomStyle = True, .[Default] = False} + ' + ' ' Create and add the child elements (properties of the style) Dim aliases1 As New Aliases() With {.Val = aliases} Dim autoredefine1 As New AutoRedefine() With {.Val = OnOffOnlyValues.Off} @@ -40,9 +96,11 @@ Module Program Dim uipriority1 As New UIPriority() With {.Val = 1} Dim unhidewhenused1 As New UnhideWhenUsed() With { .Val = OnOffOnlyValues.[On]} - If aliases <> "" Then + + If String.IsNullOrWhiteSpace(aliases) Then style.Append(aliases1) End If + style.Append(autoredefine1) style.Append(basedon1) style.Append(linkedStyle1) @@ -54,6 +112,9 @@ Module Program style.Append(nextParagraphStyle1) style.Append(uipriority1) style.Append(unhidewhenused1) + ' + + ' ' Create the StyleRunProperties object and specify some of the run properties. Dim styleRunProperties1 As New StyleRunProperties() @@ -77,6 +138,7 @@ Module Program ' Add the style to the styles part. styles.Append(style) + ' End Sub ' Add a StylesDefinitionsPart to the document. Returns a reference to it. @@ -88,4 +150,5 @@ Module Program root.Save(part) Return part End Function -End Module \ No newline at end of file +End Module +' From a887549382976c6f3668fbac06e73572480dc446 Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Mon, 13 May 2024 11:44:56 -0700 Subject: [PATCH 014/103] closes #212 --- ...ter-style-to-a-word-processing-document.md | 336 +++--------------- .../cs/Program.cs | 70 +++- .../vb/Program.vb | 172 ++++++--- 3 files changed, 243 insertions(+), 335 deletions(-) diff --git a/docs/word/how-to-create-and-add-a-character-style-to-a-word-processing-document.md b/docs/word/how-to-create-and-add-a-character-style-to-a-word-processing-document.md index 71da7845..03412755 100644 --- a/docs/word/how-to-create-and-add-a-character-style-to-a-word-processing-document.md +++ b/docs/word/how-to-create-and-add-a-character-style-to-a-word-processing-document.md @@ -12,7 +12,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 06/28/2021 +ms.date: 05/13/2024 ms.localizationpriority: medium --- # Create and add a character style to a word processing document @@ -20,36 +20,29 @@ ms.localizationpriority: medium This topic shows how to use the classes in the Open XML SDK for Office to programmatically create and add a character style to a word processing document. It contains an example -**CreateAndAddCharacterStyle** method to illustrate this task, plus a +`CreateAndAddCharacterStyle` method to illustrate this task, plus a supplemental example method to add the styles part when it is necessary. ## CreateAndAddCharacterStyle Method -The **CreateAndAddCharacterStyle** sample method can be used to add a +The `CreateAndAddCharacterStyle` sample method can be used to add a style to a word processing document. You must first obtain a reference to the style definitions part in the document to which you want to add -the style. See the Calling the Sample Method section for an example that +the style. See the [Calling the Sample Method](#calling-the-sample-method) section for an example that shows how to do this. -The method accepts four parameters that indicate: a reference to the -style definitions part, the style id of the style (an internal -identifier), the name of the style (for external use in the user -interface), and optionally, any style aliases (alternate names for use -in the user interface). +The method accepts four parameters that indicate: the path to the file to edit, +the style id of the style (an internal identifier), the name of the style +(for external use in the user interface), and optionally, any style aliases +(alternate names for use in the user interface). ### [C#](#tab/cs-0) -```csharp - public static void CreateAndAddCharacterStyle(StyleDefinitionsPart styleDefinitionsPart, - string styleid, string stylename, string aliases="") -``` +[!code-csharp[](../../samples/word/create_and_add_a_character_style/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - Public Sub CreateAndAddCharacterStyle(ByVal styleDefinitionsPart As StyleDefinitionsPart, - ByVal styleid As String, ByVal stylename As String, Optional ByVal aliases As String = "") -``` +[!code-vb[](../../samples/word/create_and_add_a_character_style/vb/Program.vb#snippet1)] *** @@ -77,7 +70,7 @@ definition. ``` -The style element styleId attribute defines the main internal identifier +The style element `styleId` attribute defines the main internal identifier of the style, the style ID (OverdueAmountChar). The aliases element specifies two alternate style names, Late Due, and Late Amount, which are comma separated. Each name must be separated by one or more commas. @@ -86,138 +79,27 @@ one typically shown in an application's user interface. ## Calling the Sample Method -You can use the **CreateAndAddCharacterStyle** +You can use the `CreateAndAddCharacterStyle` example method to create and add a named style to a word processing document using the Open XML SDK. The following code example shows how to open and obtain a reference to a word processing document, retrieve a reference to the document's style definitions part, and then call the -**CreateAndAddCharacterStyle** method. +`CreateAndAddCharacterStyle` method. -To call the method, you pass a reference to the style definitions part +To call the method, you pass a reference to the file to edit as the first parameter, the style ID of the style as the second parameter, the name of the style as the third parameter, and optionally, any style aliases as the fourth parameter. For example, the following code example creates the "Overdue Amount Char" character style in a -sample file that is named CreateAndAddCharacterStyle.docx. It also +sample file that's name comes from the first argument to the method. It also creates three runs of text in a paragraph, and applies the style to the second run. ### [C#](#tab/cs-1) -```csharp - string strDoc = @"C:\Users\Public\Documents\CreateAndAddCharacterStyle.docx"; - - using (WordprocessingDocument doc = - WordprocessingDocument.Open(strDoc, true)) - { - // Get the Styles part for this document. - StyleDefinitionsPart part = - doc.MainDocumentPart.StyleDefinitionsPart; - - // If the Styles part does not exist, add it. - if (part == null) - { - part = AddStylesPartToPackage(doc); - } - - // Create and add the character style with the style id, style name, and - // aliases specified. - CreateAndAddCharacterStyle(part, - "OverdueAmountChar", - "Overdue Amount Char", - "Late Due, Late Amount"); - - // Add a paragraph with a run with some text. - Paragraph p = - new Paragraph( - new Run( - new Text("this is some text "){Space = SpaceProcessingModeValues.Preserve})); - - // Add another run with some text. - p.AppendChild(new Run(new Text("in a run "){Space = SpaceProcessingModeValues.Preserve})); - - // Add another run with some text. - p.AppendChild(new Run(new Text("in a paragraph."){Space = SpaceProcessingModeValues.Preserve})); - - // Add the paragraph as a child element of the w:body. - doc.MainDocumentPart.Document.Body.AppendChild(p); - - // Get a reference to the second run (indexed starting with 0). - Run r = p.Descendants().ElementAtOrDefault(1); - - // If the Run has no RunProperties object, create one. - if (r.Elements().Count() == 0) - { - r.PrependChild(new RunProperties()); - } - - // Get a reference to the RunProperties. - RunProperties rPr = r.RunProperties; - - // Set the character style of the run. - if (rPr.RunStyle == null) - rPr.RunStyle = new RunStyle(); - rPr.RunStyle.Val = "OverdueAmountChar"; -``` +[!code-csharp[](../../samples/word/create_and_add_a_character_style/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-1) -```vb - Dim strDoc As String = "C:\Users\Public\Documents\CreateAndAddCharacterStyle.docx" - - Using doc As WordprocessingDocument = - WordprocessingDocument.Open(strDoc, True) - - ' Get the Styles part for this document. - Dim part As StyleDefinitionsPart = - doc.MainDocumentPart.StyleDefinitionsPart - - ' If the Styles part does not exist, add it. - If part Is Nothing Then - part = AddStylesPartToPackage(doc) - End If - - ' Create and add the character style with the style id, style name, and - ' aliases specified. - CreateAndAddCharacterStyle(part, - "OverdueAmountChar", - "Overdue Amount Char", - "Late Due, Late Amount") - - ' Add a paragraph with a run with some text. - Dim p As New Paragraph( - New Run( - New Text("This is some text ") With { _ - .Space = SpaceProcessingModeValues.Preserve})) - - ' Add another run with some text. - p.AppendChild(Of Run)(New Run(New Text("in a run ") With { _ - .Space = SpaceProcessingModeValues.Preserve})) - - ' Add another run with some text. - p.AppendChild(Of Run)(New Run(New Text("in a paragraph.") With { _ - .Space = SpaceProcessingModeValues.Preserve})) - - ' Add the paragraph as a child element of the w:body. - doc.MainDocumentPart.Document.Body.AppendChild(p) - - ' Get a reference to the second run (indexed starting with 0). - Dim r As Run = p.Descendants(Of Run)().ElementAtOrDefault(1) - - ' If the Run has no RunProperties object, create one. - If r.Elements(Of RunProperties)().Count() = 0 Then - r.PrependChild(Of RunProperties)(New RunProperties()) - End If - - ' Get a reference to the RunProperties. - Dim rPr As RunProperties = r.RunProperties - - ' Set the character style of the run. - If rPr.RunStyle Is Nothing Then - rPr.RunStyle = New RunStyle() - End If - rPr.RunStyle.Val = "OverdueAmountChar" - - End Using -``` +[!code-vb[](../../samples/word/create_and_add_a_character_style/vb/Program.vb#snippet2)] *** @@ -272,17 +154,17 @@ runs of text within a document's contents. This definition implies that the style can only define character properties (properties which apply to text within a paragraph) because it cannot be applied to paragraphs. Character styles can only be referenced by runs within a document, and -they shall be referenced by the rStyle element within a run's run -propertieselement. +they shall be referenced by the `rStyle` element within a run's run +properties element. A character style has two defining style type-specific characteristics: - The type attribute on the style has a value of character, which indicates that the following style definition is a character style. -- The style specifies only character-level properties using the rPr element. In this case, the run properties are the set of properties applied to each run which is of this style. +- The style specifies only character-level properties using the `rPr` element. In this case, the run properties are the set of properties applied to each run which is of this style. -The character style is then applied to runs by referencing the styleId -attribute value for this style in the run properties' rStyle element. +The character style is then applied to runs by referencing the `styleId` +attribute value for this style in the run properties' `rStyle` element. The following image shows some text that has had a character style applied. A character style can only be applied to a sub-paragraph level @@ -294,59 +176,29 @@ Figure 1. Text with a character style applied ## How the Code Works -The **CreateAndAddCharacterStyle** method -begins by retrieving a reference to the styles element in the styles +The `CreateAndAddCharacterStyle` method +begins by opening the specified file and retrieving a reference to the styles element in the styles part. The styles element is the root element of the part and contains all of the individual style elements. If the reference is null, the styles element is created and saved to the part. ### [C#](#tab/cs-2) -```csharp - // Get access to the root element of the styles part. - Styles styles = styleDefinitionsPart.Styles; - if (styles == null) - { - styleDefinitionsPart.Styles = new Styles(); - styleDefinitionsPart.Styles.Save(); - } -``` +[!code-csharp[](../../samples/word/create_and_add_a_character_style/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-2) -```vb - ' Get access to the root element of the styles part. - Dim styles As Styles = styleDefinitionsPart.Styles - If styles Is Nothing Then - styleDefinitionsPart.Styles = New Styles() - styleDefinitionsPart.Styles.Save() - End If -``` +[!code-vb[](../../samples/word/create_and_add_a_character_style/vb/Program.vb#snippet3)] *** ## Creating the Style -To create the style, the code instantiates the [Style](/dotnet/api/documentformat.openxml.wordprocessing.style) class and sets certain properties, -such as the [Type](/dotnet/api/documentformat.openxml.wordprocessing.style.type) of style (paragraph), the [StyleId](/dotnet/api/documentformat.openxml.wordprocessing.style.styleid), and whether the style is a [CustomStyle](/dotnet/api/documentformat.openxml.wordprocessing.style.customstyle). +To create the style, the code instantiates the class and sets certain properties, +such as the of style (paragraph), the , and whether the style is a . ### [C#](#tab/cs-3) -```csharp - // Create a new character style and specify some of the attributes. - Style style = new Style() - { - Type = StyleValues.Character, - StyleId = styleid, - CustomStyle = true - }; -``` - +[!code-csharp[](../../samples/word/create_and_add_a_character_style/cs/Program.cs#snippet4)] ### [Visual Basic](#tab/vb-3) -```vb - ' Create a new character style and specify some of the attributes. - Dim style As New Style() With { _ - .Type = StyleValues.Character, _ - .StyleId = styleid, _ - .CustomStyle = True} -``` +[!code-vb[](../../samples/word/create_and_add_a_character_style/vb/Program.vb#snippet4)] *** @@ -359,90 +211,29 @@ The code results in the following XML. The code next creates the child elements of the style, which define the properties of the style. To create an element, you instantiate its -corresponding class, and then call the [Append(\[\])](/dotnet/api/documentformat.openxml.openxmlelement.append) method to add the child element +corresponding class, and then call the method to add the child element to the style. For more information about these properties, see section 17.7 of the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification. ### [C#](#tab/cs-4) -```csharp - // Create and add the child elements (properties of the style). - Aliases aliases1 = new Aliases() { Val = aliases }; - StyleName styleName1 = new StyleName() { Val = stylename }; - LinkedStyle linkedStyle1 = new LinkedStyle() { Val = "OverdueAmountPara" }; - if (aliases != "") - style.Append(aliases1); - style.Append(styleName1); - style.Append(linkedStyle1); -``` - +[!code-csharp[](../../samples/word/create_and_add_a_character_style/cs/Program.cs#snippet5)] ### [Visual Basic](#tab/vb-4) -```vb - ' Create and add the child elements (properties of the style). - Dim aliases1 As New Aliases() With {.Val = aliases} - Dim styleName1 As New StyleName() With {.Val = stylename} - Dim linkedStyle1 As New LinkedStyle() With {.Val = "OverdueAmountPara"} - If aliases <> "" Then - style.Append(aliases1) - End If - style.Append(styleName1) - style.Append(linkedStyle1) -``` +[!code-vb[](../../samples/word/create_and_add_a_character_style/vb/Program.vb#snippet5)] *** -Next, the code instantiates a [StyleRunProperties](/dotnet/api/documentformat.openxml.wordprocessing.stylerunproperties) object to create a **rPr** (Run Properties) element. You specify the +Next, the code instantiates a +object to create a `rPr` (Run Properties) element. You specify the character properties that apply to the style, such as font and color, in -this element. The properties are then appended as children of the **rPr** element. +this element. The properties are then appended as children of the `rPr` element. -When the run properties are created, the code appends the **rPr** element to the style, and the style element +When the run properties are created, the code appends the `rPr` element to the style, and the style element to the styles root element in the styles part. ### [C#](#tab/cs-5) -```csharp - // Create the StyleRunProperties object and specify some of the run properties. - StyleRunProperties styleRunProperties1 = new StyleRunProperties(); - Bold bold1 = new Bold(); - Color color1 = new Color() { ThemeColor = ThemeColorValues.Accent2 }; - RunFonts font1 = new RunFonts() { Ascii = "Tahoma" }; - Italic italic1 = new Italic(); - // Specify a 24 point size. - FontSize fontSize1 = new FontSize() { Val = "48" }; - styleRunProperties1.Append(font1); - styleRunProperties1.Append(fontSize1); - styleRunProperties1.Append(color1); - styleRunProperties1.Append(bold1); - styleRunProperties1.Append(italic1); - - // Add the run properties to the style. - style.Append(styleRunProperties1); - - // Add the style to the styles part. - styles.Append(style); -``` - +[!code-csharp[](../../samples/word/create_and_add_a_character_style/cs/Program.cs#snippet6)] ### [Visual Basic](#tab/vb-5) -```vb - ' Create the StyleRunProperties object and specify some of the run properties. - Dim styleRunProperties1 As New StyleRunProperties() - Dim bold1 As New Bold() - Dim color1 As New Color() With { _ - .ThemeColor = ThemeColorValues.Accent2} - Dim font1 As New RunFonts() With {.Ascii = "Tahoma"} - Dim italic1 As New Italic() - ' Specify a 24 point size. - Dim fontSize1 As New FontSize() With {.Val = "48"} - styleRunProperties1.Append(font1) - styleRunProperties1.Append(fontSize1) - styleRunProperties1.Append(color1) - styleRunProperties1.Append(bold1) - styleRunProperties1.Append(italic1) - - ' Add the run properties to the style. - style.Append(styleRunProperties1) - - ' Add the style to the styles part. - styles.Append(style) -``` +[!code-vb[](../../samples/word/create_and_add_a_character_style/vb/Program.vb#snippet6)] *** @@ -466,60 +257,33 @@ The following XML shows the final style generated by the code shown here. ## Applying the Character Style Once you have the style created, you can apply it to a run by -referencing the styleId attribute value for this style in the run -properties' **rStyle** element. The following +referencing the `styleId` attribute value for this style in the run +properties' `rStyle` element. The following code example shows how to apply a style to a run referenced by the variable r. The style ID of the style to apply, OverdueAmountChar in -this example, is stored in the RunStyle property of the **rPr** object. This property represents the run -properties' **rStyle** element. +this example, is stored in the RunStyle property of the `rPr` object. This property represents the run +properties' `rStyle` element. ### [C#](#tab/cs-6) -```csharp - // If the Run has no RunProperties object, create one. - if (r.Elements().Count() == 0) - { - r.PrependChild(new RunProperties()); - } - - // Get a reference to the RunProperties. - RunProperties rPr = r.RunProperties; - - // Set the character style of the run. - if (rPr.RunStyle == null) - rPr.RunStyle = new RunStyle(); - rPr.RunStyle.Val = "OverdueAmountChar"; -``` - +[!code-csharp[](../../samples/word/create_and_add_a_character_style/cs/Program.cs#snippet7)] ### [Visual Basic](#tab/vb-6) -```vb - ' If the Run has no RunProperties object, create one. - If r.Elements(Of RunProperties)().Count() = 0 Then - r.PrependChild(Of RunProperties)(New RunProperties()) - End If - - ' Get a reference to the RunProperties. - Dim rPr As RunProperties = r.RunProperties - - ' Set the character style of the run. - If rPr.RunStyle Is Nothing Then - rPr.RunStyle = New RunStyle() - End If - rPr.RunStyle.Val = "OverdueAmountChar" -``` +[!code-vb[](../../samples/word/create_and_add_a_character_style/vb/Program.vb#snippet7)] *** ## Sample Code -The following is the complete **CreateAndAddCharacterStyle** code sample in both C\# and Visual Basic. +The following is the complete `CreateAndAddCharacterStyle` code sample in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/create_and_add_a_character_style/cs/Program.cs)] +[!code-csharp[](../../samples/word/create_and_add_a_character_style/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/create_and_add_a_character_style/vb/Program.vb)] +[!code-vb[](../../samples/word/create_and_add_a_character_style/vb/Program.vb#snippet0)] +*** ## See also [How to: Apply a style to a paragraph in a word processing document](how-to-apply-a-style-to-a-paragraph-in-a-word-processing-document.md) + [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) diff --git a/samples/word/create_and_add_a_character_style/cs/Program.cs b/samples/word/create_and_add_a_character_style/cs/Program.cs index 1a86e82b..c7a9aaf4 100644 --- a/samples/word/create_and_add_a_character_style/cs/Program.cs +++ b/samples/word/create_and_add_a_character_style/cs/Program.cs @@ -1,20 +1,28 @@ +using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System; +using System.Linq; CreateAndAddCharacterStyle(args[0], args[1], args[2], args[3]); +// // Create a new character style with the specified style id, style name and aliases and -// add it to the specified style definitions part. +// add it to the specified file. +// static void CreateAndAddCharacterStyle(string filePath, string styleid, string stylename, string aliases = "") +// { + // using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filePath, true)) { // Get access to the root element of the styles part. Styles? styles = wordprocessingDocument?.MainDocumentPart?.StyleDefinitionsPart?.Styles ?? AddStylesPartToPackage(wordprocessingDocument).Styles; + // if (styles is not null) { + // // Create a new character style and specify some of the attributes. Style style = new Style() { @@ -22,16 +30,24 @@ static void CreateAndAddCharacterStyle(string filePath, string styleid, string s StyleId = styleid, CustomStyle = true }; + // + // // Create and add the child elements (properties of the style). Aliases aliases1 = new Aliases() { Val = aliases }; StyleName styleName1 = new StyleName() { Val = stylename }; LinkedStyle linkedStyle1 = new LinkedStyle() { Val = "OverdueAmountPara" }; - if (aliases != "") + + if (!String.IsNullOrEmpty(aliases)) + { style.Append(aliases1); + } + style.Append(styleName1); style.Append(linkedStyle1); + // + // // Create the StyleRunProperties object and specify some of the run properties. StyleRunProperties styleRunProperties1 = new StyleRunProperties(); Bold bold1 = new Bold(); @@ -51,6 +67,7 @@ static void CreateAndAddCharacterStyle(string filePath, string styleid, string s // Add the style to the styles part. styles.Append(style); + // } } } @@ -69,4 +86,51 @@ static StyleDefinitionsPart AddStylesPartToPackage(WordprocessingDocument? doc) Styles root = new Styles(); root.Save(part); return part; -} \ No newline at end of file +} +// + +// +static void AddStylesToPackage(string filePath) +{ + // Create and add the character style with the style id, style name, and + // aliases specified. + CreateAndAddCharacterStyle( + filePath, + "OverdueAmountChar", + "Overdue Amount Char", + "Late Due, Late Amount"); + + using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true)) + { + + // Add a paragraph with a run with some text. + Paragraph p = new Paragraph( + new Run( + new Text("this is some text ") { Space = SpaceProcessingModeValues.Preserve })); + + // Add another run with some text. + p.AppendChild(new Run(new Text("in a run ") { Space = SpaceProcessingModeValues.Preserve })); + + // Add another run with some text. + p.AppendChild(new Run(new Text("in a paragraph.") { Space = SpaceProcessingModeValues.Preserve })); + + // Add the paragraph as a child element of the w:body. + doc?.MainDocumentPart?.Document?.Body?.AppendChild(p); + + // Get a reference to the second run (indexed starting with 0). + Run r = p.Descendants().ElementAtOrDefault(1)!; + + // + // If the Run has no RunProperties object, create one and get a reference to it. + RunProperties rPr = r.RunProperties ?? r.PrependChild(new RunProperties()); + + // Set the character style of the run. + if (rPr.RunStyle is null) + { + rPr.RunStyle = new RunStyle(); + rPr.RunStyle.Val = "OverdueAmountChar"; + } + // + } +} +// \ No newline at end of file diff --git a/samples/word/create_and_add_a_character_style/vb/Program.vb b/samples/word/create_and_add_a_character_style/vb/Program.vb index 41cc90cc..c1648184 100644 --- a/samples/word/create_and_add_a_character_style/vb/Program.vb +++ b/samples/word/create_and_add_a_character_style/vb/Program.vb @@ -1,3 +1,4 @@ +Imports DocumentFormat.OpenXml Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Wordprocessing Imports Bold = DocumentFormat.OpenXml.Wordprocessing.Bold @@ -7,56 +8,83 @@ Imports Italic = DocumentFormat.OpenXml.Wordprocessing.Italic Module Program Sub Main(args As String()) - End Sub + Dim filePath As String = args(0) + Dim styleid As String = args(1) + Dim stylename As String = args(2) + Dim aliases As String = If(args(3) Is Nothing, "", args(3)) + CreateAndAddCharacterStyle(filePath, styleid, stylename, aliases) + End Sub + ' ' Create a new character style with the specified style id, style name and aliases and add ' it to the specified style definitions part. - Public Sub CreateAndAddCharacterStyle(ByVal styleDefinitionsPart As StyleDefinitionsPart, - ByVal styleid As String, ByVal stylename As String, Optional ByVal aliases As String = "") - ' Get access to the root element of the styles part. - Dim styles As Styles = styleDefinitionsPart.Styles - If styles Is Nothing Then - styleDefinitionsPart.Styles = New Styles() - styleDefinitionsPart.Styles.Save() - End If - - ' Create a new character style and specify some of the attributes. - Dim style As New Style() With { - .Type = StyleValues.Character, - .StyleId = styleid, - .CustomStyle = True} - - ' Create and add the child elements (properties of the style). - Dim aliases1 As New Aliases() With {.Val = aliases} - Dim styleName1 As New StyleName() With {.Val = stylename} - Dim linkedStyle1 As New LinkedStyle() With {.Val = "OverdueAmountPara"} - If aliases <> "" Then - style.Append(aliases1) - End If - style.Append(styleName1) - style.Append(linkedStyle1) - - ' Create the StyleRunProperties object and specify some of the run properties. - Dim styleRunProperties1 As New StyleRunProperties() - Dim bold1 As New Bold() - Dim color1 As New Color() With { - .ThemeColor = ThemeColorValues.Accent2} - Dim font1 As New RunFonts() With {.Ascii = "Tahoma"} - Dim italic1 As New Italic() - ' Specify a 24 point size. - Dim fontSize1 As New FontSize() With {.Val = "48"} - styleRunProperties1.Append(font1) - styleRunProperties1.Append(fontSize1) - styleRunProperties1.Append(color1) - styleRunProperties1.Append(bold1) - styleRunProperties1.Append(italic1) - - ' Add the run properties to the style. - style.Append(styleRunProperties1) - - ' Add the style to the styles part. - styles.Append(style) + ' + Public Sub CreateAndAddCharacterStyle(ByVal filePath As String, ByVal styleid As String, ByVal stylename As String, Optional ByVal aliases As String = "") + ' + + ' Open the document for editing. + ' + Using doc As WordprocessingDocument = WordprocessingDocument.Open(filePath, True) + Dim styleDefinitionsPart As StyleDefinitionsPart = doc.MainDocumentPart.StyleDefinitionsPart + + If styleDefinitionsPart Is Nothing Then + styleDefinitionsPart = AddStylesPartToPackage(doc) + End If + ' + + ' Get access to the root element of the styles part. + Dim styles As Styles = styleDefinitionsPart.Styles + If styles Is Nothing Then + styleDefinitionsPart.Styles = New Styles() + styleDefinitionsPart.Styles.Save() + End If + + ' + ' Create a new character style and specify some of the attributes. + Dim style As New Style() With { + .Type = StyleValues.Character, + .StyleId = styleid, + .CustomStyle = True} + ' + + ' + ' Create and add the child elements (properties of the style). + Dim aliases1 As New Aliases() With {.Val = aliases} + Dim styleName1 As New StyleName() With {.Val = stylename} + Dim linkedStyle1 As New LinkedStyle() With {.Val = "OverdueAmountPara"} + + If aliases <> "" Then + style.Append(aliases1) + End If + + style.Append(styleName1) + style.Append(linkedStyle1) + ' + + ' + ' Create the StyleRunProperties object and specify some of the run properties. + Dim styleRunProperties1 As New StyleRunProperties() + Dim bold1 As New Bold() + Dim color1 As New Color() With { + .ThemeColor = ThemeColorValues.Accent2} + Dim font1 As New RunFonts() With {.Ascii = "Tahoma"} + Dim italic1 As New Italic() + ' Specify a 24 point size. + Dim fontSize1 As New FontSize() With {.Val = "48"} + styleRunProperties1.Append(font1) + styleRunProperties1.Append(fontSize1) + styleRunProperties1.Append(color1) + styleRunProperties1.Append(bold1) + styleRunProperties1.Append(italic1) + + ' Add the run properties to the style. + style.Append(styleRunProperties1) + + ' Add the style to the styles part. + styles.Append(style) + ' + End Using End Sub ' Add a StylesDefinitionsPart to the document. Returns a reference to it. @@ -68,4 +96,56 @@ Module Program root.Save(part) Return part End Function + ' + + ' + Public Sub AddStylesToPackage(ByVal filePath As String) + ' Create and add the character style with the style id, style name, and + ' aliases specified. + CreateAndAddCharacterStyle(filePath, + "OverdueAmountChar", + "Overdue Amount Char", + "Late Due, Late Amount") + + Using doc As WordprocessingDocument = WordprocessingDocument.Open(filePath, True) + + + ' Add a paragraph with a run with some text. + Dim p As New Paragraph( + New Run( + New Text("This is some text ") With { + .Space = SpaceProcessingModeValues.Preserve})) + + ' Add another run with some text. + p.AppendChild(Of Run)(New Run(New Text("in a run ") With { + .Space = SpaceProcessingModeValues.Preserve})) + + ' Add another run with some text. + p.AppendChild(Of Run)(New Run(New Text("in a paragraph.") With { + .Space = SpaceProcessingModeValues.Preserve})) + + ' Add the paragraph as a child element of the w:body. + doc.MainDocumentPart.Document.Body.AppendChild(p) + + ' Get a reference to the second run (indexed starting with 0). + Dim r As Run = p.Descendants(Of Run)().ElementAtOrDefault(1) + + ' + ' If the Run has no RunProperties object, create one. + If r.Elements(Of RunProperties)().Count() = 0 Then + r.PrependChild(Of RunProperties)(New RunProperties()) + End If + + ' Get a reference to the RunProperties. + Dim rPr As RunProperties = r.RunProperties + + ' Set the character style of the run. + If rPr.RunStyle Is Nothing Then + rPr.RunStyle = New RunStyle() + End If + rPr.RunStyle.Val = "OverdueAmountChar" + ' + End Using + End Sub + ' End Module \ No newline at end of file From bb1f6346d22434aa3169f4cfb9ea285f1ee03131 Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Mon, 13 May 2024 13:58:37 -0700 Subject: [PATCH 015/103] closes #211 --- ...ssing-document-by-providing-a-file-name.md | 59 ++++++++----------- .../cs/Program.cs | 6 ++ .../vb/Program.vb | 10 +++- 3 files changed, 37 insertions(+), 38 deletions(-) diff --git a/docs/word/how-to-create-a-word-processing-document-by-providing-a-file-name.md b/docs/word/how-to-create-a-word-processing-document-by-providing-a-file-name.md index b4af6ddd..6a572ae2 100644 --- a/docs/word/how-to-create-a-word-processing-document-by-providing-a-file-name.md +++ b/docs/word/how-to-create-a-word-processing-document-by-providing-a-file-name.md @@ -11,7 +11,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 05/13/2024 ms.localizationpriority: high --- # Create a word processing document by providing a file name @@ -23,6 +23,7 @@ Office to programmatically create a word processing document. -------------------------------------------------------------------------------- ## Creating a WordprocessingDocument Object + In the Open XML SDK, the class represents a Word document package. To create a Word document, you create an instance of the class and @@ -31,41 +32,30 @@ 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. -To create the class instance you call the [Create(String, WordprocessingDocumentType)](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.create) -method. Several [Create()](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.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 +To create the class instance you call the +method. Several 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 takes a full path string that represents the document that you want to create. The second parameter is a member of the enumeration. This parameter represents the type of document. For example, there is a -different member of the **WordProcessingDocumentType** enumeration for each +different member of the `WordProcessingDocumentType` enumeration for each of document, template, and the macro enabled variety of document and template. > [!NOTE] -> Carefully select the appropriate **WordProcessingDocumentType** and verify that the persisted file has the correct, matching file extension. If the **>WordProcessingDocumentType** does not match the file extension, an error occurs when you open the file in Microsoft Word. +> Carefully select the appropriate `WordProcessingDocumentType` and verify that the persisted file has the correct, matching file extension. If the `WordProcessingDocumentType` does not match the file extension, an error occurs when you open the file in Microsoft Word. -The code that calls the **Create** method is -part of a **using** statement followed by a +The code that calls the `Create` method is +part of a `using` statement followed by a bracketed block, as shown in the following code example. ### [C#](#tab/cs-0) -```csharp - using (WordprocessingDocument wordDocument = - WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document)) - { - // Insert other code here. - } -``` - +[!code-csharp[](../../samples/word/create_by_providing_a_file_name/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - Using wordDocument As WordprocessingDocument = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document) - ' Insert other code here. - End Using -``` +[!code-vb[](../../samples/word/create_by_providing_a_file_name/vb/Program.vb#snippet1)] *** [!include[Using Statement](../includes/using-statement.md)] @@ -81,14 +71,15 @@ you can set about adding the document structure and text. -------------------------------------------------------------------------------- ## Generating the WordprocessingML Markup + To create the basic document structure using the Open XML SDK, you -instantiate the **Document** class, assign it -to the **Document** property of the main -document part, and then add instances of the **Body**, **Paragraph**, -**Run** and **Text** +instantiate the `Document` class, assign it +to the `Document` property of the main +document part, and then add instances of the `Body`, `Paragraph`, +`Run` and `Text` classes. This is shown in the sample code listing, and does the work of generating the required WordprocessingML markup. While the code in the -sample listing calls the **AppendChild** method +sample listing calls the `AppendChild` method of each class, you can sometimes make code shorter and easier to read by using the technique shown in the following code example. @@ -110,20 +101,15 @@ using the technique shown in the following code example. -------------------------------------------------------------------------------- ## Sample Code -The **CreateWordprocessingDocument** method can +The `CreateWordprocessingDocument` method can be used to create a basic Word document. You call it by passing a full path as the only parameter. The following code example creates the Invoice.docx file in the Public Documents folder. ### [C#](#tab/cs-2) -```csharp - CreateWordprocessingDocument(@"c:\Users\Public\Documents\Invoice.docx"); -``` - +[!code-csharp[](../../samples/word/create_by_providing_a_file_name/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-2) -```vb - CreateWordprocessingDocument("c:\Users\Public\Documents\Invoice.docx") -``` +[!code-vb[](../../samples/word/create_by_providing_a_file_name/vb/Program.vb#snippet2)] *** @@ -134,10 +120,11 @@ parameter in the call to the **Create** method. Following is the complete code example in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/create_by_providing_a_file_name/cs/Program.cs)] +[!code-csharp[](../../samples/word/create_by_providing_a_file_name/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/create_by_providing_a_file_name/vb/Program.vb)] +[!code-vb[](../../samples/word/create_by_providing_a_file_name/vb/Program.vb#snippet0)] +*** -------------------------------------------------------------------------------- ## See also diff --git a/samples/word/create_by_providing_a_file_name/cs/Program.cs b/samples/word/create_by_providing_a_file_name/cs/Program.cs index d2417d83..c531ef35 100644 --- a/samples/word/create_by_providing_a_file_name/cs/Program.cs +++ b/samples/word/create_by_providing_a_file_name/cs/Program.cs @@ -3,13 +3,18 @@ using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; +// CreateWordprocessingDocument(args[0]); +// +// static void CreateWordprocessingDocument(string filepath) { // Create a document by supplying the filepath. + // using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document)) { + // // Add a main document part. MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); @@ -20,4 +25,5 @@ static void CreateWordprocessingDocument(string filepath) Run run = para.AppendChild(new Run()); run.AppendChild(new Text("Create text in body - CreateWordprocessingDocument")); } + // } diff --git a/samples/word/create_by_providing_a_file_name/vb/Program.vb b/samples/word/create_by_providing_a_file_name/vb/Program.vb index 5a7a6919..e2f92a8d 100644 --- a/samples/word/create_by_providing_a_file_name/vb/Program.vb +++ b/samples/word/create_by_providing_a_file_name/vb/Program.vb @@ -6,12 +6,17 @@ Imports DocumentFormat.OpenXml.Wordprocessing Module MyModule Sub Main(args As String()) + ' + CreateWordprocessingDocument(args(0)) + ' End Sub + ' Public Sub CreateWordprocessingDocument(ByVal filepath As String) ' Create a document by supplying the filepath. - Using wordDocument As WordprocessingDocument = - WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document) + ' + Using wordDocument As WordprocessingDocument = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document) + ' ' Add a main document part. Dim mainPart As MainDocumentPart = wordDocument.AddMainDocumentPart() @@ -24,4 +29,5 @@ Module MyModule run.AppendChild(New Text("Create text in body - CreateWordprocessingDocument")) End Using End Sub + ' End Module \ No newline at end of file From 1d5930b2774ce46994ecfe3165b8edb661d8f20e Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Mon, 13 May 2024 15:11:24 -0700 Subject: [PATCH 016/103] closes #210 --- ...t-from-the-docm-to-the-docx-file-format.md | 151 +++--------------- .../cs/Program.cs | 19 ++- .../vb/Program.vb | 18 ++- 3 files changed, 58 insertions(+), 130 deletions(-) diff --git a/docs/word/how-to-convert-a-word-processing-document-from-the-docm-to-the-docx-file-format.md b/docs/word/how-to-convert-a-word-processing-document-from-the-docm-to-the-docx-file-format.md index 645aa7ad..7e82f772 100644 --- a/docs/word/how-to-convert-a-word-processing-document-from-the-docm-to-the-docx-file-format.md +++ b/docs/word/how-to-convert-a-word-processing-document-from-the-docm-to-the-docx-file-format.md @@ -13,7 +13,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 06/28/2021 +ms.date: 05/13/2024 ms.localizationpriority: high --- @@ -22,27 +22,22 @@ ms.localizationpriority: high This topic shows how to use the classes in the Open XML SDK for Office to programmatically convert a Microsoft Word document that contains VBA code (and has a .docm extension) to a standard document (with a .docx extension). It contains an example -**ConvertDOCMtoDOCX** method to illustrate this task. +`ConvertDOCMtoDOCX` method to illustrate this task. ## ConvertDOCMtoDOCX Method -The **ConvertDOCMtoDOCX** sample method can be used to convert a Word document that contains VBA code (and has a .docm +The `ConvertDOCMtoDOCX` sample method can be used to convert a Word document that contains VBA code (and has a .docm extension) to a standard document (with a .docx extension). Use this method to remove the macros and the vbaProject part that contains them from a document stored in .docm file format. The method accepts a single parameter that indicates the file name of the file to convert. ### [C#](#tab/cs-0) -```csharp - public static void ConvertDOCMtoDOCX(string fileName) -``` - +[!code-csharp[](../../samples/word/convert_from_the_docm_to_the_docx_file_format/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - Public Sub ConvertDOCMtoDOCX(ByVal fileName As String) -``` +[!code-vb[](../../samples/word/convert_from_the_docm_to_the_docx_file_format/vb/Program.vb#snippet1)] *** @@ -54,16 +49,9 @@ To call the sample method, pass a string that contains the name of the file to convert. The following sample code shows an example. ### [C#](#tab/cs-1) -```csharp - string filename = @"C:\Users\Public\Documents\WithMacros.docm"; - ConvertDOCMtoDOCX(filename); -``` - +[!code-csharp[](../../samples/word/convert_from_the_docm_to_the_docx_file_format/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-1) -```vb - Dim filename As String = "C:\Users\Public\Documents\WithMacros.docm" - ConvertDOCMtoDOCX(filename) -``` +[!code-vb[](../../samples/word/convert_from_the_docm_to_the_docx_file_format/vb/Program.vb#snippet2)] *** @@ -76,7 +64,7 @@ contain content equivalent to an external XML file, binary file, image file, and so on, depending on the type. The standard that defines how Open XML documents are stored in .zip files is called the Open Packaging Conventions. For more information about the Open Packaging Conventions, -see [ISO/IEC 29500-2](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51459). +see [ISO/IEC 29500-2:2021](https://www.iso.org/standard/77818.html). When you create and save a VBA macro in a document, Word adds a new binary part named vbaProject that contains the internal representation @@ -88,6 +76,7 @@ vbaProject part is highlighted. Figure 1. The vbaProject part ![vbaProject part shown in the Document Explorer](../media/OpenXMLCon_HowToConvertDOCMtoDOCX_Fig1.gif) + The task of converting a macro enabled document to one that is not macro enabled therefore consists largely of removing the vbaProject part from the document package. @@ -99,87 +88,32 @@ the document contains a vbaProject part, and deleting the part. After the code deletes the part, it changes the document type internally and renames the document so that it uses the .docx extension. -The code starts by opening the document by using the **Open** method and indicating that the document should be open for read/write access (the final true parameter). The code then retrieves a reference to the Document part by using the **MainDocumentPart** property of the word processing document. +The code starts by opening the document by using the `Open` method and indicating that the document should be open for read/write access (the final true parameter). The code then retrieves a reference to the Document part by using the `MainDocumentPart` property of the word processing document. ### [C#](#tab/cs-2) -```csharp - using (WordprocessingDocument document = - WordprocessingDocument.Open(fileName, true)) - { - // Get access to the main document part. - var docPart = document.MainDocumentPart; - // Code removed here… - } -``` - +[!code-csharp[](../../samples/word/convert_from_the_docm_to_the_docx_file_format/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-2) -```vb - Using document As WordprocessingDocument = - WordprocessingDocument.Open(fileName, True) - - ' Access the main document part. - Dim docPart = document.MainDocumentPart - ' Code removed here… - End Using -``` -*** +[!code-vb[](../../samples/word/convert_from_the_docm_to_the_docx_file_format/vb/Program.vb#snippet3)] +`* -The sample code next verifies that the vbaProject part exists, deletes the part and saves the document. The code has no effect if the file to convert does not contain a vbaProject part. To find the part, the sample code retrieves the **VbaProjectPart** property of the document. It calls the **DeletePart** method to delete the part, and then calls the **Save** method of the document to save the changes. +The sample code next verifies that the vbaProject part exists, deletes the part and saves the document. The code has no effect if the file to convert does not contain a vbaProject part. To find the part, the sample code retrieves the `VbaProjectPart` property of the document. It calls the `DeletePart` method to delete the part, and then calls the `Save` method of the document to save the changes. ### [C#](#tab/cs-3) -```csharp - // Look for the vbaProject part. If it is there, delete it. - var vbaPart = docPart.VbaProjectPart; - if (vbaPart != null) - { - // Delete the vbaProject part and then save the document. - docPart.DeletePart(vbaPart); - docPart.Document.Save(); - // Code removed here. - } -``` - +[!code-csharp[](../../samples/word/convert_from_the_docm_to_the_docx_file_format/cs/Program.cs#snippet4)] ### [Visual Basic](#tab/vb-3) -```vb - ' Look for the vbaProject part. If it is there, delete it. - Dim vbaPart = docPart.VbaProjectPart - If vbaPart IsNot Nothing Then - - ' Delete the vbaProject part and then save the document. - docPart.DeletePart(vbaPart) - docPart.Document.Save() - ' Code removed here… - End If -``` +[!code-vb[](../../samples/word/convert_from_the_docm_to_the_docx_file_format/vb/Program.vb#snippet4)] *** -It is not enough to delete the part from the document. You must also convert the document type, internally. The Open XML SDK provides a way to perform this task: You can call the document **ChangeDocumentType** method and indicate the new document type (in this case, supply the *WordProcessingDocumentType.Document* enumerated value). +It is not enough to delete the part from the document. You must also convert the document type, internally. The Open XML SDK provides a way to perform this task: You can call the document `ChangeDocumentType` method and indicate the new document type (in this case, supply the enumerated value). -You must also rename the file. However, you cannot do that while the file is open. The using block closes the file at the end of the block. Therefore, you must have some way to indicate to the code after the block that you have modified the file: The **fileChanged** Boolean variable tracks this information for you. +You must also rename the file. However, you cannot do that while the file is open. The using block closes the file at the end of the block. Therefore, you must have some way to indicate to the code after the block that you have modified the file: The `fileChanged` Boolean variable tracks this information for you. ### [C#](#tab/cs-4) -```csharp - // Change the document type to - // not macro-enabled. - document.ChangeDocumentType( - WordprocessingDocumentType.Document); - - // Track that the document has been changed. - fileChanged = true; -``` - +[!code-csharp[](../../samples/word/convert_from_the_docm_to_the_docx_file_format/cs/Program.cs#snippet4)] ### [Visual Basic](#tab/vb-4) -```vb - ' Change the document type to - ' not macro-enabled. - document.ChangeDocumentType( - WordprocessingDocumentType.Document) - - ' Track that the document has been changed. - fileChanged = True -``` +[!code-vb[](../../samples/word/convert_from_the_docm_to_the_docx_file_format/vb/Program.vb#snippet4)] *** @@ -189,56 +123,23 @@ output file exists and deletes it, and finally moves the file from the old file name to the new file name. ### [C#](#tab/cs-5) -```csharp - // If anything goes wrong in this file handling, - // the code will raise an exception back to the caller. - if (fileChanged) - { - // Create the new .docx filename. - var newFileName = Path.ChangeExtension(fileName, ".docx"); - - // If it already exists, it will be deleted! - if (File.Exists(newFileName)) - { - File.Delete(newFileName); - } - - // Rename the file. - File.Move(fileName, newFileName); - } -``` - +[!code-csharp[](../../samples/word/convert_from_the_docm_to_the_docx_file_format/cs/Program.cs#snippet6)] ### [Visual Basic](#tab/vb-5) -```vb - ' If anything goes wrong in this file handling, - ' the code will raise an exception back to the caller. - If fileChanged Then - - ' Create the new .docx filename. - Dim newFileName = Path.ChangeExtension(fileName, ".docx") - - ' If it already exists, it will be deleted! - If File.Exists(newFileName) Then - File.Delete(newFileName) - End If - - ' Rename the file. - File.Move(fileName, newFileName) - End If -``` +[!code-vb[](../../samples/word/convert_from_the_docm_to_the_docx_file_format/vb/Program.vb#snippet6)] *** ## Sample Code -The following is the complete **ConvertDOCMtoDOCX** code sample in C\# and Visual +The following is the complete `ConvertDOCMtoDOCX` code sample in C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/convert_from_the_docm_to_the_docx_file_format/cs/Program.cs)] +[!code-csharp[](../../samples/word/convert_from_the_docm_to_the_docx_file_format/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/convert_from_the_docm_to_the_docx_file_format/vb/Program.vb)] +[!code-vb[](../../samples/word/convert_from_the_docm_to_the_docx_file_format/vb/Program.vb#snippet0)] +*** ## See also diff --git a/samples/word/convert_from_the_docm_to_the_docx_file_format/cs/Program.cs b/samples/word/convert_from_the_docm_to_the_docx_file_format/cs/Program.cs index 33a31ef4..c9d00033 100644 --- a/samples/word/convert_from_the_docm_to_the_docx_file_format/cs/Program.cs +++ b/samples/word/convert_from_the_docm_to_the_docx_file_format/cs/Program.cs @@ -3,19 +3,27 @@ using System; using System.IO; +// ConvertDOCMtoDOCX(args[0]); +// // Given a .docm file (with macro storage), remove the VBA // project, reset the document type, and save the document with a new name. +// +// static void ConvertDOCMtoDOCX(string fileName) +// { + // bool fileChanged = false; using (WordprocessingDocument document = WordprocessingDocument.Open(fileName, true)) { // Access the main document part. var docPart = document.MainDocumentPart ?? throw new ArgumentNullException("MainDocumentPart is null."); + // + // // Look for the vbaProject part. If it is there, delete it. var vbaPart = docPart.VbaProjectPart; if (vbaPart is not null) @@ -23,17 +31,20 @@ static void ConvertDOCMtoDOCX(string fileName) // Delete the vbaProject part and then save the document. docPart.DeletePart(vbaPart); docPart.Document.Save(); + // + // // Change the document type to // not macro-enabled. - document.ChangeDocumentType( - WordprocessingDocumentType.Document); + document.ChangeDocumentType(WordprocessingDocumentType.Document); // Track that the document has been changed. fileChanged = true; + // } } + // // If anything goes wrong in this file handling, // the code will raise an exception back to the caller. if (fileChanged) @@ -50,4 +61,6 @@ static void ConvertDOCMtoDOCX(string fileName) // Rename the file. File.Move(fileName, newFileName); } -} \ No newline at end of file + // +} +// diff --git a/samples/word/convert_from_the_docm_to_the_docx_file_format/vb/Program.vb b/samples/word/convert_from_the_docm_to_the_docx_file_format/vb/Program.vb index f47f5c16..20aea40b 100644 --- a/samples/word/convert_from_the_docm_to_the_docx_file_format/vb/Program.vb +++ b/samples/word/convert_from_the_docm_to_the_docx_file_format/vb/Program.vb @@ -4,21 +4,29 @@ Imports DocumentFormat.OpenXml.Packaging Module Program Sub Main(args As String()) + ' + ConvertDOCMtoDOCX(args(0)) + ' End Sub ' Given a .docm file (with macro storage), remove the VBA ' project, reset the document type, and save the document with a new name. + ' + ' Public Sub ConvertDOCMtoDOCX(ByVal fileName As String) + ' + ' Dim fileChanged As Boolean = False - Using document As WordprocessingDocument = - WordprocessingDocument.Open(fileName, True) + Using document As WordprocessingDocument = WordprocessingDocument.Open(fileName, True) ' Access the main document part. Dim docPart = document.MainDocumentPart + ' + ' ' Look for the vbaProject part. If it is there, delete it. Dim vbaPart = docPart.VbaProjectPart If vbaPart IsNot Nothing Then @@ -26,7 +34,9 @@ Module Program ' Delete the vbaProject part and then save the document. docPart.DeletePart(vbaPart) docPart.Document.Save() + ' + ' ' Change the document type to ' not macro-enabled. document.ChangeDocumentType( @@ -34,9 +44,11 @@ Module Program ' Track that the document has been changed. fileChanged = True + ' End If End Using + ' ' If anything goes wrong in this file handling, ' the code will raise an exception back to the caller. If fileChanged Then @@ -52,5 +64,7 @@ Module Program ' Rename the file. File.Move(fileName, newFileName) End If + ' End Sub + ' End Module \ No newline at end of file From 59fb086ff1e0fd547ff00e17386b7d2eb7be5e61 Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Mon, 13 May 2024 16:40:56 -0700 Subject: [PATCH 017/103] closes #209 --- ...ackage-part-to-a-document-part-in-a-dif.md | 2 +- ...heme-part-in-a-word-processing-document.md | 2 +- ...rch-and-replace-text-in-a-document-part.md | 2 +- ...add-tables-to-word-processing-documents.md | 2 +- ...ientation-of-a-word-processing-document.md | 250 ++++-------------- .../cs/Program.cs | 61 +++-- .../vb/Program.vb | 53 +++- 7 files changed, 131 insertions(+), 241 deletions(-) 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 dbfbf88a..11d86267 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 @@ -33,7 +33,7 @@ programmatically. To open an existing document, instantiate the class as shown in 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. +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. 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 5b499b48..41d38e3b 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 @@ -29,7 +29,7 @@ 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 + method, with the Boolean parameter set to **true** to enable editing the document. ### [C#](#tab/cs-0) 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 9e57abad..d970c5fc 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 @@ -32,7 +32,7 @@ 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 +**** method, with the Boolean parameter set to **true** to enable editing the document. ### [C#](#tab/cs-0) 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..42342073 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 @@ -165,7 +165,7 @@ Before you can insert a table into a document, you must create the [Table](/dotn *** -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 [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 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. ## Fill the table with data diff --git a/docs/word/how-to-change-the-print-orientation-of-a-word-processing-document.md b/docs/word/how-to-change-the-print-orientation-of-a-word-processing-document.md index 75bf8f58..0c614792 100644 --- a/docs/word/how-to-change-the-print-orientation-of-a-word-processing-document.md +++ b/docs/word/how-to-change-the-print-orientation-of-a-word-processing-document.md @@ -12,7 +12,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 06/28/2021 +ms.date: 05/13/2024 ms.localizationpriority: medium --- @@ -20,7 +20,7 @@ ms.localizationpriority: medium This topic shows how to use the classes in the Open XML SDK for Office to programmatically set the print orientation of a Microsoft Word document. It contains an example -**SetPrintOrientation** method to illustrate this task. +`SetPrintOrientation` method to illustrate this task. @@ -28,25 +28,17 @@ Office to programmatically set the print orientation of a Microsoft Word documen ## SetPrintOrientation Method -You can use the **SetPrintOrientation** method +You can use the `SetPrintOrientation` method to change the print orientation of a word processing document. The method accepts two parameters that indicate the name of the document to -modify (string) and the new print orientation ([PageOrientationValues](/dotnet/api/documentformat.openxml.wordprocessing.pageorientationvalues)). +modify (string) and the new print orientation (). -The following code shows the **SetPrintOrientation** method. +The following code shows the `SetPrintOrientation` method. ### [C#](#tab/cs-0) -```csharp - public static void SetPrintOrientation( - string fileName, PageOrientationValues newOrientation) -``` - +[!code-csharp[](../../samples/word/change_the_print_orientation/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - Public Sub SetPrintOrientation( - ByVal fileName As String, - ByVal newOrientation As PageOrientationValues) -``` +[!code-vb[](../../samples/word/change_the_print_orientation/vb/Program.vb#snippet1)] *** @@ -59,21 +51,14 @@ the width, height, and margins for each section. ## Calling the Sample SetPrintOrientation Method -To call the sample **SetPrintOrientation** -method, pass a string that contains the name of the file to convert. The -following code shows an example method call. +To call the sample `SetPrintOrientation` +method, pass a string that contains the name of the file to convert and the string "landscape" or "portrait" +depending on which orientation you want. The following code shows an example method call. ### [C#](#tab/cs-1) -```csharp - SetPrintOrientation(@"C:\Users\Public\Documents\ChangePrintOrientation.docx", - PageOrientationValues.Landscape); -``` - +[!code-csharp[](../../samples/word/change_the_print_orientation/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-1) -```vb - SetPrintOrientation("C:\Users\Public\Documents\ChangePrintOrientation.docx", - PageOrientationValues.Landscape) -``` +[!code-vb[](../../samples/word/change_the_print_orientation/vb/Program.vb#snippet2)] *** @@ -81,40 +66,22 @@ following code shows an example method call. ## How the Code Works -The following code first opens the document by using the [Open](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) method and sets the **isEditable** parameter to -**true** to indicate that the document should +The following code first determines which orientation to apply and +then opens the document by using the +method and sets the `isEditable` parameter to +`true` to indicate that the document should be read/write. The code maintains a Boolean variable that tracks whether the document has changed (so that it can save the document later, if the document has changed). The code retrieves a reference to the main document part, and then uses that reference to retrieve a collection of -all of the descendants of type [SectionProperties](/dotnet/api/documentformat.openxml.wordprocessing.sectionproperties) within the content of the +all of the descendants of type within the content of the document. Later code will use this collection to set the orientation for each section in turn. ### [C#](#tab/cs-2) -```csharp - using (var document = - WordprocessingDocument.Open(fileName, true)) - { - bool documentChanged = false; - - var docPart = document.MainDocumentPart; - var sections = docPart.Document.Descendants(); - // Code removed here... - } -``` - +[!code-csharp[](../../samples/word/change_the_print_orientation/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-2) -```vb - Using document = - WordprocessingDocument.Open(fileName, True) - Dim documentChanged As Boolean = False - - Dim docPart = document.MainDocumentPart - Dim sections = docPart.Document.Descendants(Of SectionProperties)() - ' Code removed here... - End Using -``` +[!code-vb[](../../samples/word/change_the_print_orientation/vb/Program.vb#snippet3)] *** @@ -122,35 +89,12 @@ each section in turn. ## Iterating Through All the Sections -The next block of code iterates through all the sections in the collection of **SectionProperties** elements. For each section, the code initializes a variable that tracks whether the page orientation for the section was changed so the code can update the page size and margins. (If the new orientation matches the original orientation, the code will not update the page.) The code continues by retrieving a reference to the first [PageSize](/dotnet/api/documentformat.openxml.wordprocessing.pagesize) descendant of the **SectionProperties** element. If the reference is not null, the code updates the orientation as required. +The next block of code iterates through all the sections in the collection of `SectionProperties` elements. For each section, the code initializes a variable that tracks whether the page orientation for the section was changed so the code can update the page size and margins. (If the new orientation matches the original orientation, the code will not update the page.) The code continues by retrieving a reference to the first descendant of the `SectionProperties` element. If the reference is not null, the code updates the orientation as required. ### [C#](#tab/cs-3) -```csharp - foreach (SectionProperties sectPr in sections) - { - bool pageOrientationChanged = false; - - PageSize pgSz = sectPr.Descendants().FirstOrDefault(); - if (pgSz != null) - { - // Code removed here... - } - } -``` - +[!code-csharp[](../../samples/word/change_the_print_orientation/cs/Program.cs#snippet4)] ### [Visual Basic](#tab/vb-3) -```vb - For Each sectPr As SectionProperties In sections - - Dim pageOrientationChanged As Boolean = False - - Dim pgSz As PageSize = - sectPr.Descendants(Of PageSize).FirstOrDefault - If pgSz IsNot Nothing Then - ' Code removed here... - End If - Next -``` +[!code-vb[](../../samples/word/change_the_print_orientation/vb/Program.vb#snippet4)] *** @@ -158,61 +102,26 @@ The next block of code iterates through all the sections in the collection of ** ## Setting the Orientation for the Section -The next block of code first checks whether the [Orient](/dotnet/api/documentformat.openxml.wordprocessing.pagesize.orient) property of the **PageSize** element exists. As with many properties +The next block of code first checks whether the +property of the `PageSize` element exists. As with many properties of Open XML elements, the property or attribute might not exist yet. In that case, retrieving the property returns a null reference. By default, if the property does not exist, and the new orientation is Portrait, the -code will not update the page. If the **Orient** property already exists, and its value +code will not update the page. If the `Orient` property already exists, and its value differs from the new orientation value supplied as a parameter to the -method, the code sets the **Value** property of -the **Orient** property, and sets both the -**pageOrientationChanged** and the **documentChanged** flags. (The code uses the **pageOrientationChanged** flag to determine whether it -must update the page size and margins. It uses the **documentChanged** flag to determine whether it must +method, the code sets the `Value` property of +the `Orient` property, and sets both the +`pageOrientationChanged` and the `documentChanged` flags. (The code uses the `pageOrientationChanged` flag to determine whether it +must update the page size and margins. It uses the `documentChanged` flag to determine whether it must save the document at the end.) > [!NOTE] -> If the code must create the **Orient** property, it must also create the value to store in the property, as a new [EnumValue\](/dotnet/api/documentformat.openxml.enumvalue-1) instance, supplying the new orientation in the **EnumValue** constructor. +> If the code must create the `Orient` property, it must also create the value to store in the property, as a new instance, supplying the new orientation in the `EnumValue` constructor. ### [C#](#tab/cs-4) -```csharp - if (pgSz.Orient == null) - { - if (newOrientation != PageOrientationValues.Portrait) - { - pageOrientationChanged = true; - documentChanged = true; - pgSz.Orient = - new EnumValue(newOrientation); - } - } - else - { - if (pgSz.Orient.Value != newOrientation) - { - pgSz.Orient.Value = newOrientation; - pageOrientationChanged = true; - documentChanged = true; - } - } -``` - +[!code-csharp[](../../samples/word/change_the_print_orientation/cs/Program.cs#snippet5)] ### [Visual Basic](#tab/vb-4) -```vb - If pgSz.Orient Is Nothing Then - If newOrientation <> PageOrientationValues.Portrait Then - pageOrientationChanged = True - documentChanged = True - pgSz.Orient = - New EnumValue(Of PageOrientationValues)(newOrientation) - End If - Else - If pgSz.Orient.Value <> newOrientation Then - pgSz.Orient.Value = newOrientation - pageOrientationChanged = True - documentChanged = True - End If - End If -``` +[!code-vb[](../../samples/word/change_the_print_orientation/vb/Program.vb#snippet5)] *** @@ -224,34 +133,12 @@ At this point in the code, the page orientation may have changed. If so, the code must complete two more tasks. It must update the page size, and update the page margins for the section. The first task is easy—the following code just swaps the page height and width, storing the values -in the **PageSize** element. +in the `PageSize` element. ### [C#](#tab/cs-5) -```csharp - if (pageOrientationChanged) - { - // Changing the orientation is not enough. You must also - // change the page size. - var width = pgSz.Width; - var height = pgSz.Height; - pgSz.Width = height; - pgSz.Height = width; - // Code removed here... - } -``` - +[!code-csharp[](../../samples/word/change_the_print_orientation/cs/Program.cs#snippet6)] ### [Visual Basic](#tab/vb-5) -```vb - If pageOrientationChanged Then - ' Changing the orientation is not enough. You must also - ' change the page size. - Dim width = pgSz.Width - Dim height = pgSz.Height - pgSz.Width = height - pgSz.Height = width - ' Code removed here... - End If -``` +[!code-vb[](../../samples/word/change_the_print_orientation/vb/Program.vb#snippet6)] *** @@ -261,53 +148,17 @@ in the **PageSize** element. The next step in the sample procedure handles margins for the section. If the page orientation has changed, the code must rotate the margins to -match. To do so, the code retrieves a reference to the [PageMargin](/dotnet/api/documentformat.openxml.wordprocessing.pagemargin) element for the section. If the -element exists, the code rotates the margins. Note that the code rotates +match. To do so, the code retrieves a reference to the element for the section. If the element exists, the code rotates the margins. Note that the code rotates the margins by 90 degrees—some printers rotate the margins by 270 degrees instead and you could modify the code to take that into account. -Also be aware that the [Top](/dotnet/api/documentformat.openxml.wordprocessing.pagemargin.top) and [Bottom](/dotnet/api/documentformat.openxml.wordprocessing.pagemargin.bottom) properties of the **PageMargin** object are signed values, and the -[Left](/dotnet/api/documentformat.openxml.wordprocessing.pagemargin.left) and [Right](/dotnet/api/documentformat.openxml.wordprocessing.pagemargin.right) properties are unsigned values. The -code must convert between the two types of values as it rotates the +Also be aware that the and properties of the `PageMargin` object are signed values, and the + and properties are unsigned values. The code must convert between the two types of values as it rotates the margin settings, as shown in the following code. ### [C#](#tab/cs-6) -```csharp - PageMargin pgMar = - sectPr.Descendants().FirstOrDefault(); - if (pgMar != null) - { - var top = pgMar.Top.Value; - var bottom = pgMar.Bottom.Value; - var left = pgMar.Left.Value; - var right = pgMar.Right.Value; - - pgMar.Top = new Int32Value((int)left); - pgMar.Bottom = new Int32Value((int)right); - pgMar.Left = - new UInt32Value((uint)System.Math.Max(0, bottom)); - pgMar.Right = - new UInt32Value((uint)System.Math.Max(0, top)); - } -``` - +[!code-csharp[](../../samples/word/change_the_print_orientation/cs/Program.cs#snippet7)] ### [Visual Basic](#tab/vb-6) -```vb - Dim pgMar As PageMargin = - sectPr.Descendants(Of PageMargin).FirstOrDefault() - If pgMar IsNot Nothing Then - Dim top = pgMar.Top.Value - Dim bottom = pgMar.Bottom.Value - Dim left = pgMar.Left.Value - Dim right = pgMar.Right.Value - - pgMar.Top = CType(left, Int32Value) - pgMar.Bottom = CType(right, Int32Value) - pgMar.Left = CType(System.Math.Max(0, - CType(bottom, Int32Value)), UInt32Value) - pgMar.Right = CType(System.Math.Max(0, - CType(top, Int32Value)), UInt32Value) - End If -``` +[!code-vb[](../../samples/word/change_the_print_orientation/vb/Program.vb#snippet7)] *** @@ -319,19 +170,9 @@ After all the modifications, the code determines whether the document has changed. If the document has changed, the code saves it. ### [C#](#tab/cs-7) -```csharp - if (documentChanged) - { - docPart.Document.Save(); - } -``` - +[!code-csharp[](../../samples/word/change_the_print_orientation/cs/Program.cs#snippet8)] ### [Visual Basic](#tab/vb-7) -```vb - If documentChanged Then - docPart.Document.Save() - End If -``` +[!code-vb[](../../samples/word/change_the_print_orientation/vb/Program.vb#snippet8)] *** @@ -339,14 +180,15 @@ has changed. If the document has changed, the code saves it. ## Sample Code -The following is the complete **SetPrintOrientation** code sample in C\# and Visual +The following is the complete `SetPrintOrientation` code sample in C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/change_the_print_orientation/cs/Program.cs)] +[!code-csharp[](../../samples/word/change_the_print_orientation/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/change_the_print_orientation/vb/Program.vb)] +[!code-vb[](../../samples/word/change_the_print_orientation/vb/Program.vb#snippet0)] +*** ----------------------------------------------------------------------------- diff --git a/samples/word/change_the_print_orientation/cs/Program.cs b/samples/word/change_the_print_orientation/cs/Program.cs index fa990838..4d9ca6cc 100644 --- a/samples/word/change_the_print_orientation/cs/Program.cs +++ b/samples/word/change_the_print_orientation/cs/Program.cs @@ -1,49 +1,62 @@ -#nullable enable - using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System; +using System.Collections.Generic; using System.Linq; +// SetPrintOrientation(args[0], args[1]); +// // Given a document name, set the print orientation for // all the sections of the document. -static void SetPrintOrientation(string fileName, string no) +// +// +static void SetPrintOrientation(string fileName, string orientation) + // { - PageOrientationValues newOrientation = no.ToLower() switch + // + PageOrientationValues newOrientation = orientation.ToLower() switch { "landscape" => PageOrientationValues.Landscape, "portrait" => PageOrientationValues.Portrait, - _ => throw new System.ArgumentException("Invalid argument: " + no) + _ => throw new System.ArgumentException("Invalid argument: " + orientation) }; - using (var document = - WordprocessingDocument.Open(fileName, true)) + using (var document = WordprocessingDocument.Open(fileName, true)) { bool documentChanged = false; - if (document.MainDocumentPart is null) + if (document?.MainDocumentPart?.Document.Body is null) { throw new ArgumentNullException("MainDocumentPart and/or Body is null."); } - var docPart = document.MainDocumentPart; + Body docBody = document.MainDocumentPart.Document.Body; + IEnumerable sections = docBody.ChildElements.OfType(); - var sections = docPart.Document.Descendants(); + if (sections.Count() == 0) + { + docBody.AddChild(new SectionProperties()); + sections = docBody.ChildElements.OfType(); + } + // + + // foreach (SectionProperties sectPr in sections) { bool pageOrientationChanged = false; - PageSize pgSz = sectPr.Descendants().First(); + PageSize pgSz = sectPr.ChildElements.OfType().FirstOrDefault() ?? sectPr.AppendChild(new PageSize() { Width = 12240, Height = 15840 }); // No Orient property? Create it now. Otherwise, just - // set its value. Assume that the default orientation - // is Portrait. + // set its value. Assume that the default orientation is Portrait. + // if (pgSz.Orient is null) + // { // Need to create the attribute. You do not need to // create the Orient property if the property does not @@ -53,8 +66,7 @@ static void SetPrintOrientation(string fileName, string no) { pageOrientationChanged = true; documentChanged = true; - pgSz.Orient = - new EnumValue(newOrientation); + pgSz.Orient = new EnumValue(newOrientation); } } else @@ -67,7 +79,9 @@ static void SetPrintOrientation(string fileName, string no) pageOrientationChanged = true; documentChanged = true; } + // + // if (pageOrientationChanged) { // Changing the orientation is not enough. You must also @@ -76,8 +90,10 @@ static void SetPrintOrientation(string fileName, string no) var height = pgSz.Height; pgSz.Width = height; pgSz.Height = width; + // - PageMargin pgMar = (sectPr.Descendants().FirstOrDefault()) ?? throw new ArgumentNullException("There are no PageMargin elements in the section."); + // + PageMargin? pgMar = sectPr.Descendants().FirstOrDefault(); if (pgMar is not null) { @@ -98,17 +114,20 @@ static void SetPrintOrientation(string fileName, string no) pgMar.Top = new Int32Value((int)left); pgMar.Bottom = new Int32Value((int)right); - pgMar.Left = - new UInt32Value((uint)System.Math.Max(0, bottom)); - pgMar.Right = - new UInt32Value((uint)System.Math.Max(0, top)); + pgMar.Left = new UInt32Value((uint)System.Math.Max(0, bottom)); + pgMar.Right = new UInt32Value((uint)System.Math.Max(0, top)); } + // } } } + + // if (documentChanged) { - docPart.Document.Save(); + document.MainDocumentPart.Document.Save(); } + // } } +// \ No newline at end of file diff --git a/samples/word/change_the_print_orientation/vb/Program.vb b/samples/word/change_the_print_orientation/vb/Program.vb index 587b64ae..dba52b5c 100644 --- a/samples/word/change_the_print_orientation/vb/Program.vb +++ b/samples/word/change_the_print_orientation/vb/Program.vb @@ -4,28 +4,52 @@ Imports DocumentFormat.OpenXml.Wordprocessing Module Program Sub Main(args As String()) + ' + SetPrintOrientation(args(0), args(1)) + ' End Sub ' Given a document name, set the print orientation for ' all the sections of the document. - Public Sub SetPrintOrientation( - ByVal fileName As String, ByVal newOrientation As PageOrientationValues) - Using document = - WordprocessingDocument.Open(fileName, True) + + ' + ' + Public Sub SetPrintOrientation(ByVal fileName As String, ByVal orientation As String) + ' + + ' + Dim newOrientation As PageOrientationValues + + Select Case orientation + Case "landscape" + newOrientation = PageOrientationValues.Landscape + Case "portrait" + newOrientation = PageOrientationValues.Portrait + Case Else + Throw New ArgumentException("Invalid orientation") + End Select + + + Using document = WordprocessingDocument.Open(fileName, True) Dim documentChanged As Boolean = False Dim docPart = document.MainDocumentPart Dim sections = docPart.Document.Descendants(Of SectionProperties)() + ' + ' For Each sectPr As SectionProperties In sections Dim pageOrientationChanged As Boolean = False - Dim pgSz As PageSize = - sectPr.Descendants(Of PageSize).FirstOrDefault + Dim pgSz As PageSize = sectPr.Descendants(Of PageSize).FirstOrDefault + + ' If pgSz IsNot Nothing Then + ' + ' No Orient property? Create it now. Otherwise, just ' set its value. Assume that the default orientation ' is Portrait. @@ -49,7 +73,9 @@ Module Program documentChanged = True End If End If + ' + ' If pageOrientationChanged Then ' Changing the orientation is not enough. You must also ' change the page size. @@ -57,9 +83,10 @@ Module Program Dim height = pgSz.Height pgSz.Width = height pgSz.Height = width + ' - Dim pgMar As PageMargin = - sectPr.Descendants(Of PageMargin).FirstOrDefault() + ' + Dim pgMar As PageMargin = sectPr.Descendants(Of PageMargin).FirstOrDefault() If pgMar IsNot Nothing Then ' Rotate margins. Printer settings control how far you ' rotate when switching to landscape mode. Not having those @@ -73,18 +100,20 @@ Module Program pgMar.Top = CType(left, Int32Value) pgMar.Bottom = CType(right, Int32Value) - pgMar.Left = CType(System.Math.Max(0, - CType(bottom, Int32Value)), UInt32Value) - pgMar.Right = CType(System.Math.Max(0, - CType(top, Int32Value)), UInt32Value) + pgMar.Left = CType(System.Math.Max(0, CType(bottom, Int32Value)), UInt32Value) + pgMar.Right = CType(System.Math.Max(0, CType(top, Int32Value)), UInt32Value) End If + ' End If End If Next + ' If documentChanged Then docPart.Document.Save() End If + ' End Using End Sub + ' End Module \ No newline at end of file From c1de6cbc9160686de74d6eb7a31494c9a1644ac9 Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Tue, 14 May 2024 11:00:07 -0700 Subject: [PATCH 018/103] closes #208 --- ...n-a-table-in-a-word-processing-document.md | 116 ++++++------------ .../word/change_text_a_table/cs/Program.cs | 16 ++- .../word/change_text_a_table/vb/Program.vb | 13 +- 3 files changed, 58 insertions(+), 87 deletions(-) diff --git a/docs/word/how-to-change-text-in-a-table-in-a-word-processing-document.md b/docs/word/how-to-change-text-in-a-table-in-a-word-processing-document.md index bc951426..d59a555c 100644 --- a/docs/word/how-to-change-text-in-a-table-in-a-word-processing-document.md +++ b/docs/word/how-to-change-text-in-a-table-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: 05/14/2024 ms.localizationpriority: high --- @@ -23,40 +23,28 @@ This topic shows how to use the Open XML SDK for Office to programmatically chan ## Open the Existing Document -To open an existing document, instantiate the class as shown in the following **using** statement. In the same statement, open the word processing file at the specified **filepath** by using the **Open** method, with the Boolean parameter set to **true** to enable editing the document. +To open an existing document, instantiate the class as shown in the following `using` statement. In the same statement, open the word processing file at the specified `filepath` by using the `Open` method, with the Boolean parameter set to `true` to enable editing the document. ### [C#](#tab/cs-0) -```csharp - using (WordprocessingDocument doc = - WordprocessingDocument.Open(filepath, true)) - { - // Insert other code here. - } -``` - +[!code-csharp[](../../samples/word/change_text_a_table/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - Using doc As WordprocessingDocument = WordprocessingDocument.Open(filepath, True) - ' Insert other code here. - End Using -``` +[!code-vb[](../../samples/word/change_text_a_table/vb/Program.vb#snippet1)] *** [!include[Using Statement](../includes/using-statement.md)] ## The Structure of a Table -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 +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. +more `t` elements. The `t` element contains a range of text. -The document might contain a table as in this example. A **table** is a set of paragraphs (and other block-level -content) arranged in **rows** and **columns**. Tables in **WordprocessingML** are defined via the **tbl** element, which is analogous to the HTML table -tag. Consider an empty one-cell table (that is, a table with one row and +The document might contain a table as in this example. A `table` is a set of paragraphs (and other block-level +content) arranged in `rows` and `columns`. Tables in `WordprocessingML` are defined via the `tbl` element, which is analogous to the HTML table tag. Consider an empty one-cell table (that is, a table with one row and one column) and 1 point borders on all sides. This table is represented -by the following **WordprocessingML** code +by the following `WordprocessingML` code example. ```xml @@ -85,43 +73,23 @@ example. ``` This table specifies table-wide properties of 100% of page width using -the **tblW** element, a set of table borders -using the **tblBorders** element, the table +the `tblW` element, a set of table borders +using the `tblBorders` element, the table grid, which defines a set of shared vertical edges within the table -using the **tblGrid** element, and a single -table row using the **tr** element. +using the `tblGrid` element, and a single +table row using the `tr` element. ## How the Sample Code Works -In the sample code, after you open the document in the **using** statement, you locate the first table in +In the sample code, after you open the document in the `using` statement, you locate the first table in the document. Then you locate the second row in the table by finding the row whose index is 1. Next, you locate the third cell in that row whose index is 2, as shown in the following code example. ### [C#](#tab/cs-1) -```csharp - // Find the first table in the document. - Table table = - doc.MainDocumentPart.Document.Body.Elements().First(); - - // Find the second row in the table. - TableRow row = table.Elements().ElementAt(1); - - // Find the third cell in the row. - TableCell cell = row.Elements().ElementAt(2); -``` - +[!code-csharp[](../../samples/word/change_text_a_table/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-1) -```vb - ' Find the first table in the document. - Dim table As Table = doc.MainDocumentPart.Document.Body.Elements(Of Table)().First() - - ' Find the second row in the table. - Dim row As TableRow = table.Elements(Of TableRow)().ElementAt(1) - - ' Find the third cell in the row. - Dim cell As TableCell = row.Elements(Of TableCell)().ElementAt(2) -``` +[!code-vb[](../../samples/word/change_text_a_table/vb/Program.vb#snippet2)] *** @@ -130,20 +98,9 @@ first paragraph of the cell and replace the text with the passed in text. The following code example shows these actions. ### [C#](#tab/cs-2) -```csharp - Paragraph p = cell.Elements().First(); - Run r = p.Elements().First(); - Text t = r.Elements().First(); - t.Text = txt; -``` - +[!code-csharp[](../../samples/word/change_text_a_table/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-2) -```vb - Dim p As Paragraph = cell.Elements(Of Paragraph)().First() - Dim r As Run = p.Elements(Of Run)().First() - Dim t As Text = r.Elements(Of Text)().First() - t.Text = txt -``` +[!code-vb[](../../samples/word/change_text_a_table/vb/Program.vb#snippet3)] *** @@ -152,55 +109,52 @@ text. The following code example shows these actions. The following code example shows how to change the text in the specified table cell in a word processing document. The code example expects that the document, whose file name and path are passed as an argument to the -**ChangeTextInCell** method, contains a table. +`ChangeTextInCell` method, contains a table. The code example also expects that the table has at least two rows and three columns, and that the table contains text in the cell that is located at the second row and the third column position. When you call -the **ChangeTextInCell** method in your +the `ChangeTextInCell` method in your program, the text in the cell at the specified location will be replaced -by the text that you pass in as the second argument to the **ChangeTextInCell** method. In the following table -the text "The text from the API example" was used. +by the text that you pass in as the second argument to the `ChangeTextInCell` method. | **Some text** | **Some text** | **Some text** | |---------------|---------------|---------------| -| Some text | Some text |The text from the API example | +| Some text | Some text |The text from the second argument | ## Sample Code -The **ChangeTextinCell** method changes the +The `ChangeTextInCell` method changes the text in the second row and the third column of the first table found in the file. You call it by passing a full path to the file as the first parameter, and the text to use as the second parameter. For example, the -following call to the **ChangeTextInCell** +following call to the `ChangeTextInCell` method changes the text in the specified cell to "The text from the API example." ### [C#](#tab/cs-3) -```csharp - ChangeTextInCell(@"c:\Users\Public\Documents\word4.docx", - "The text from the API example"); -``` - +[!code-csharp[](../../samples/word/change_text_a_table/cs/Program.cs#snippet4)] ### [Visual Basic](#tab/vb-3) -```vb - ChangeTextInCell("C:\Users\Public\Documents\word4.docx", _ - "The text from the API example") -``` +[!code-vb[](../../samples/word/change_text_a_table/vb/Program.vb#snippet4)] *** Following is the complete code example. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/change_text_a_table/cs/Program.cs)] +[!code-csharp[](../../samples/word/change_text_a_table/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/change_text_a_table/vb/Program.vb)] +[!code-vb[](../../samples/word/change_text_a_table/vb/Program.vb#snippet0)] +*** ## See also [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) + [How to: Change Text in a Table in a Word Processing Document](/previous-versions/office/developer/office-2010/cc840870(v=office.14)) + [Language-Integrated Query (LINQ)](/previous-versions/bb397926(v=vs.140)) + [Extension Methods (C\# Programming Guide)](/dotnet/csharp/programming-guide/classes-and-structs/extension-methods) + [Extension Methods (Visual Basic)](/dotnet/visual-basic/programming-guide/language-features/procedures/extension-methods) diff --git a/samples/word/change_text_a_table/cs/Program.cs b/samples/word/change_text_a_table/cs/Program.cs index f90b3714..b3a269db 100644 --- a/samples/word/change_text_a_table/cs/Program.cs +++ b/samples/word/change_text_a_table/cs/Program.cs @@ -2,21 +2,26 @@ using DocumentFormat.OpenXml.Wordprocessing; using System; using System.Linq; - +// ChangeTextInCell(args[0], args[1]); +// +// // Change the text in a table in a word processing document. static void ChangeTextInCell(string filePath, string txt) { // Use the file name and path passed in as an argument to - // open an existing document. + // open an existing document. + // using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true)) + // { if (doc.MainDocumentPart is null || doc.MainDocumentPart.Document.Body is null) { throw new ArgumentNullException("MainDocumentPart and/or Body is null."); } + // // Find the first table in the document. Table table = doc.MainDocumentPart.Document.Body.Elements
().First(); @@ -25,7 +30,8 @@ static void ChangeTextInCell(string filePath, string txt) // Find the third cell in the row. TableCell cell = row.Elements().ElementAt(2); - + // + // // Find the first paragraph in the table cell. Paragraph p = cell.Elements().First(); @@ -35,5 +41,7 @@ static void ChangeTextInCell(string filePath, string txt) // Set the text for the run. Text t = r.Elements().First(); t.Text = txt; + // } -} \ No newline at end of file +} +// \ No newline at end of file diff --git a/samples/word/change_text_a_table/vb/Program.vb b/samples/word/change_text_a_table/vb/Program.vb index f7508208..61b922ea 100644 --- a/samples/word/change_text_a_table/vb/Program.vb +++ b/samples/word/change_text_a_table/vb/Program.vb @@ -3,15 +3,21 @@ Imports DocumentFormat.OpenXml.Wordprocessing Module Program Sub Main(args As String()) + ' + ChangeTextInCell(args(0), args(1)) + ' End Sub - + ' ' Change the text in a table in a word processing document. Public Sub ChangeTextInCell(ByVal filepath As String, ByVal txt As String) ' Use the file name and path passed in as an argument to ' Open an existing document. + ' Using doc As WordprocessingDocument = WordprocessingDocument.Open(filepath, True) + ' + ' ' Find the first table in the document. Dim table As Table = doc.MainDocumentPart.Document.Body.Elements(Of Table)().First() @@ -20,7 +26,8 @@ Module Program ' Find the third cell in the row. Dim cell As TableCell = row.Elements(Of TableCell)().ElementAt(2) - + ' + ' ' Find the first paragraph in the table cell. Dim p As Paragraph = cell.Elements(Of Paragraph)().First() @@ -30,6 +37,8 @@ Module Program ' Set the text for the run. Dim t As Text = r.Elements(Of Text)().First() t.Text = txt + ' End Using End Sub + ' End Module \ No newline at end of file From 0cf5f64e943b8ac2601b78f6f839d356fa47f240 Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Tue, 10 Sep 2024 16:23:35 -0700 Subject: [PATCH 019/103] closes #207 --- ...paragraph-in-a-word-processing-document.md | 473 +++--------------- .../cs/Program.cs | 34 +- .../vb/Program.vb | 36 +- 3 files changed, 122 insertions(+), 421 deletions(-) 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..4373d951 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 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 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