Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
2b284b6
fix presentation samples
mikeebowen Oct 27, 2023
5944149
cs files updated for nullable enable
tomjebo Oct 28, 2023
dc486c2
fix nullable issues in spreadsheet
mikeebowen Oct 27, 2023
99d7f9e
Merge pull request #1 from tomjebo/fix-nullable-references
mikeebowen Oct 31, 2023
a4e2d58
Merge branch 'main' into fix-nullable-references
mikeebowen Oct 31, 2023
ec2b10f
make word examples executable
mikeebowen Oct 31, 2023
06a0984
make recommended changes
mikeebowen Nov 1, 2023
cac8345
replace NullableRefernceExceptions with ArgumentNullExceptions
mikeebowen Nov 2, 2023
c9a56a3
use .First() to prevent nullable value
mikeebowen Nov 2, 2023
dd2e343
fix nullable issue
mikeebowen Nov 2, 2023
84bcebc
migrage code samples to their own files
mikeebowen Nov 3, 2023
c4e25f4
Merge remote-tracking branch 'upstream/main' into extract-common-elem…
mikeebowen Nov 6, 2023
827d526
fix links to sample code
mikeebowen Nov 9, 2023
cae6dac
Merge branch 'main' of github.com:OfficeDev/open-xml-docs into extrac…
mikeebowen Nov 9, 2023
f37d3bb
fix links to sample code 2
mikeebowen Nov 9, 2023
c5779ab
change CSharp to C#
mikeebowen Nov 9, 2023
2b50ca2
move code snippets into tabs
mikeebowen Nov 10, 2023
0b199ff
fix additional issues
mikeebowen Nov 10, 2023
788f57b
fix issues with files
mikeebowen Nov 10, 2023
38f4b8c
fix vb issues
mikeebowen Nov 12, 2023
9283f4e
fix vb files
mikeebowen Nov 12, 2023
7f35851
fix errors in migrator
mikeebowen Nov 13, 2023
ed60e11
run validators
mikeebowen Nov 13, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,24 +21,7 @@ This topic shows how to use the classes in the Open XML SDK for
Office to add a document part (file) that receives a relationship **Id** parameter for a word
processing document.

The following assembly directives are required to compile the code in
this topic.

```csharp
using System.IO;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.Xml;
```

```vb
Imports System.IO
Imports DocumentFormat.OpenXml
Imports DocumentFormat.OpenXml.Packaging
Imports DocumentFormat.OpenXml.Wordprocessing
Imports System.Xml
```

-----------------------------------------------------------------------------
## Packages and Document Parts
Expand All @@ -59,211 +42,34 @@ a word-processing document package.

[!include[Structure](../includes/word/structure.md)]

-----------------------------------------------------------------------------
## How the Sample Code Works
The sample code, in this how-to, starts by passing in a parameter that
represents the path to the Word document. It then creates a document as
a **WordprocessingDocument** object.

```csharp
public static void AddNewPart(string document)
{
// Create a new word processing document.
WordprocessingDocument wordDoc =
WordprocessingDocument.Create(document,
WordprocessingDocumentType.Document);
```

```vb
Public Shared Sub AddNewPart(ByVal document As String)
' Create a new word processing document.
Dim wordDoc As WordprocessingDocument = _
WordprocessingDocument.Create(document, WordprocessingDocumentType.Document)
```

It then adds the **MainDocumentPart** part in
the new word processing document, with the relationship ID, **rId1**. It also adds the **CustomFilePropertiesPart** part and a **CoreFilePropertiesPart** in the new word processing
document.

```csharp
// Add the MainDocumentPart part in the new word processing document.
MainDocumentPart mainDocPart = wordDoc.AddNewPart<MainDocumentPart>
("application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", "rId1");
mainDocPart.Document = new Document();

// Add the CustomFilePropertiesPart part in the new word processing document.
CustomFilePropertiesPart customFilePropPart = wordDoc.AddCustomFilePropertiesPart();
customFilePropPart.Properties = new DocumentFormat.OpenXml.CustomProperties.Properties();

// Add the CoreFilePropertiesPart part in the new word processing document.
CoreFilePropertiesPart coreFilePropPart = wordDoc.AddCoreFilePropertiesPart();

using (XmlTextWriter writer =
new XmlTextWriter(coreFilePropPart.GetStream(FileMode.Create), System.Text.Encoding.UTF8))
{
writer.WriteRaw("<?xml version=\"1.0\" encoding=\"UTF-
8\"?>\r\n<cp:coreProperties xmlns:cp=\
"https://schemas.openxmlformats.org/package/2006/metadata/core-properties\"></cp:coreProperties>");
writer.Flush();
}
```

```vb
' Add the MainDocumentPart part in the new word processing document.
Dim mainDocPart As MainDocumentPart = wordDoc.AddNewPart(Of MainDocumentPart) _
("application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", "rId1") _
mainDocPart.Document = New Document()

' Add the CustomFilePropertiesPart part in the new word processing document.
Dim customFilePropPart As CustomFilePropertiesPart = wordDoc.AddCustomFilePropertiesPart()
customFilePropPart.Properties = New DocumentFormat.OpenXml.CustomProperties.Properties()

' Add the CoreFilePropertiesPart part in the new word processing document.
Dim coreFilePropPart As CoreFilePropertiesPart = wordDoc.AddCoreFilePropertiesPart()

Using writer As New XmlTextWriter(coreFilePropPart.GetStream(FileMode.Create), System.Text.Encoding.UTF8)
writer.WriteRaw("<?xml version=""1.0"" encoding=""UTF-8""?>" _
& vbCrLf & "<cp:coreProperties xmlns:cp=""https://schemas.openxmlformats.org/package/2006/metadata/core-properties""></cp:coreProperties>")
writer.Flush()
End Using
```

The code then adds the **DigitalSignatureOriginPart** part, the **ExtendedFilePropertiesPart** part, and the **ThumbnailPart** part in the new word processing
document with realtionship IDs rId4, rId5, and rId6. And then it closes
the **wordDoc** object.

```csharp
// Add the DigitalSignatureOriginPart part in the new word processing document.
wordDoc.AddNewPart<DigitalSignatureOriginPart>("rId4");

// Add the ExtendedFilePropertiesPart part in the new word processing document.**
ExtendedFilePropertiesPart extendedFilePropPart = wordDoc.AddNewPart<ExtendedFilePropertiesPart>("rId5");
extendedFilePropPart.Properties = new DocumentFormat.OpenXml.ExtendedProperties.Properties();

// Add the ThumbnailPart part in the new word processing document.
wordDoc.AddNewPart<ThumbnailPart>("image/jpeg", "rId6");

wordDoc.Close();
```

```vb
' Add the DigitalSignatureOriginPart part in the new word processing document.
wordDoc.AddNewPart(Of DigitalSignatureOriginPart)("rId4")

' Add the ExtendedFilePropertiesPart part in the new word processing document.**
Dim extendedFilePropPart As ExtendedFilePropertiesPart = wordDoc.AddNewPart(Of ExtendedFilePropertiesPart)("rId5")
extendedFilePropPart.Properties = New DocumentFormat.OpenXml.ExtendedProperties.Properties()

' Add the ThumbnailPart part in the new word processing document.
wordDoc.AddNewPart(Of ThumbnailPart)("image/jpeg", "rId6")

wordDoc.Close()
```

> [!NOTE]
> The **AddNewPart&lt;T&gt;** method creates a relationship from the current document part to the new document part. This method returns the new document part. Also, you can use the **[DataPart.FeedData](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.datapart.feeddata.aspx)** method to fill the document part.

-----------------------------------------------------------------------------
## Sample Code
The following code, adds a new document part that contains custom XML
from an external file and then populates the document part. You can call
the method **AddNewPart** by using a call like
the following code example.

### [C#](#tab/cs-0)
```csharp
string document = @"C:\Users\Public\Documents\MyPkg1.docx";
AddNewPart(document);
```

### [Visual Basic](#tab/vb-0)
```vb
Dim document As String = "C:\Users\Public\Documents\MyPkg1.docx"
AddNewPart(document)
```
***

The following is the complete code example in both C\# and Visual Basic.

```csharp
public static void AddNewPart(string document)
{
// Create a new word processing document.
WordprocessingDocument wordDoc =
WordprocessingDocument.Create(document,
WordprocessingDocumentType.Document);

// Add the MainDocumentPart part in the new word processing document.
var mainDocPart = wordDoc.AddNewPart<MainDocumentPart>
("application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", "rId1");
mainDocPart.Document = new Document();

// Add the CustomFilePropertiesPart part in the new word processing document.
var customFilePropPart = wordDoc.AddCustomFilePropertiesPart();
customFilePropPart.Properties = new DocumentFormat.OpenXml.CustomProperties.Properties();

// Add the CoreFilePropertiesPart part in the new word processing document.
var coreFilePropPart = wordDoc.AddCoreFilePropertiesPart();
using (XmlTextWriter writer = new
XmlTextWriter(coreFilePropPart.GetStream(FileMode.Create), System.Text.Encoding.UTF8))
{
writer.WriteRaw("<?xml version=
\"1.0\" encoding=\"UTF-8\"?>\r\n<cp:coreProperties xmlns:cp=\
"https://schemas.openxmlformats.org/package/2006/metadata/core-properties\"></cp:coreProperties>");
writer.Flush();
}

// Add the DigitalSignatureOriginPart part in the new word processing document.
wordDoc.AddNewPart<DigitalSignatureOriginPart>("rId4");

// Add the ExtendedFilePropertiesPart part in the new word processing document.
var extendedFilePropPart = wordDoc.AddNewPart<ExtendedFilePropertiesPart>("rId5");
extendedFilePropPart.Properties =
new DocumentFormat.OpenXml.ExtendedProperties.Properties();

// Add the ThumbnailPart part in the new word processing document.
wordDoc.AddNewPart<ThumbnailPart>("image/jpeg", "rId6");
The following is the complete code example in both C\# and Visual Basic.

wordDoc.Close();
}
```
### [C#](#tab/cs)
[!code-csharp[](../../samples/word/add_a_new_part_that_receives_a_relationship_id_to_a_package/cs/Program.cs)]

```vb
Public Sub AddNewPart(ByVal document As String)
' Create a new word processing document.
Dim wordDoc As WordprocessingDocument = _
WordprocessingDocument.Create(document, WordprocessingDocumentType.Document)

' Add the MainDocumentPart part in the new word processing document.
Dim mainDocPart = wordDoc.AddNewPart(Of MainDocumentPart) _
("application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", "rId1")
mainDocPart.Document = New Document()

' Add the CustomFilePropertiesPart part in the new word processing document.
Dim customFilePropPart = wordDoc.AddCustomFilePropertiesPart()
customFilePropPart.Properties = New DocumentFormat.OpenXml.CustomProperties.Properties()

' Add the CoreFilePropertiesPart part in the new word processing document.
Dim coreFilePropPart = wordDoc.AddCoreFilePropertiesPart()
Using writer As New XmlTextWriter(coreFilePropPart.GetStream(FileMode.Create), _
System.Text.Encoding.UTF8)
writer.WriteRaw( _
"<?xml version=""1.0"" encoding=""UTF-8""?>" & vbCr & vbLf & _
"<cp:coreProperties xmlns:cp=""https://schemas.openxmlformats.org/package/2006/metadata/core-properties""></cp:coreProperties>")
writer.Flush()
End Using

' Add the DigitalSignatureOriginPart part in the new word processing document.
wordDoc.AddNewPart(Of DigitalSignatureOriginPart)("rId4")

' Add the ExtendedFilePropertiesPart part in the new word processing document.
Dim extendedFilePropPart = wordDoc.AddNewPart(Of ExtendedFilePropertiesPart)("rId5")
extendedFilePropPart.Properties = _
New DocumentFormat.OpenXml.ExtendedProperties.Properties()

' Add the ThumbnailPart part in the new word processing document.
wordDoc.AddNewPart(Of ThumbnailPart)("image/jpeg", "rId6")

wordDoc.Close()
End Sub
```
### [Visual Basic](#tab/vb)
[!code-vb[](../../samples/word/add_a_new_part_that_receives_a_relationship_id_to_a_package/vb/Program.vb)]

-----------------------------------------------------------------------------
## See also
Expand Down
57 changes: 16 additions & 41 deletions docs/general/how-to-add-a-new-document-part-to-a-package.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,7 @@ ms.localizationpriority: medium

This topic shows how to use the classes in the Open XML SDK for Office to add a document part (file) to a word processing document programmatically.

The following assembly directives are required to compile the code in this topic.

```csharp
using System.IO;
using DocumentFormat.OpenXml.Packaging;
```

```vb
Imports System.IO
Imports DocumentFormat.OpenXml.Packaging
```

## Packages and document parts

Expand All @@ -37,18 +27,22 @@ An Open XML document is stored as a package, whose format is defined by [ISO/IEC

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.

### [C#](#tab/cs-0)
```csharp
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
{
// Insert other code here.
}
```

### [Visual Basic](#tab/vb-0)
```vb
Using wordDoc As WordprocessingDocument = WordprocessingDocument.Open(document, True)
' Insert other code here.
End Using
```
***


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
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**.
Expand All @@ -63,6 +57,7 @@ file that contains the custom XML and writes it to the **CustomXmlPart** part.
> [!NOTE]
> To use the new document part in the document, add a link to the document part in the relationship part for the new part.

### [C#](#tab/cs-1)
```csharp
MainDocumentPart mainPart = wordDoc.MainDocumentPart;
CustomXmlPart myXmlPart = mainPart.AddCustomXmlPart(CustomXmlPartType.CustomXml);
Expand All @@ -73,6 +68,7 @@ file that contains the custom XML and writes it to the **CustomXmlPart** part.
}
```

### [Visual Basic](#tab/vb-1)
```vb
Dim mainPart As MainDocumentPart = wordDoc.MainDocumentPart

Expand All @@ -82,60 +78,39 @@ file that contains the custom XML and writes it to the **CustomXmlPart** part.
myXmlPart.FeedData(stream)
End Using
```
***


## Sample code

The following code adds a new document part that contains custom XML from an external file and then populates the part. To call the AddCustomXmlPart method in your program, use the following example that modifies the file "myPkg2.docx" by adding a new document part to it.

### [C#](#tab/cs-2)
```csharp
string document = @"C:\Users\Public\Documents\myPkg2.docx";
string fileName = @"C:\Users\Public\Documents\myXML.xml";
AddNewPart(document, fileName);
```

### [Visual Basic](#tab/vb-2)
```vb
Dim document As String = "C:\Users\Public\Documents\myPkg2.docx"
Dim fileName As String = "C:\Users\Public\Documents\myXML.xml"
AddNewPart(document, fileName)
```
***


> [!NOTE]
> Before you run the program, change the Word file extension from .docx to .zip, and view the content of the zip file. Then change the extension back to .docx and run the program. After running the program, change the file extension again to .zip and view its content. You will see an extra folder named &quot;customXML.&quot; This folder contains the XML file that represents the added part

Following is the complete code example in both C\# and Visual Basic.

```csharp
// To add a new document part to a package.
public static void AddNewPart(string document, string fileName)
{
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
{
MainDocumentPart mainPart = wordDoc.MainDocumentPart;

CustomXmlPart myXmlPart = mainPart.AddCustomXmlPart(CustomXmlPartType.CustomXml);

using (FileStream stream = new FileStream(fileName, FileMode.Open))
{
myXmlPart.FeedData(stream);
}
}
}
```
### [C#](#tab/cs)
[!code-csharp[](../../samples/word/add_a_new_part_to_a_package/cs/Program.cs)]

```vb
' To add a new document part to a package.
Public Sub AddNewPart(ByVal document As String, ByVal fileName As String)
Using wordDoc As WordprocessingDocument = WordprocessingDocument.Open(document, True)
Dim mainPart As MainDocumentPart = wordDoc.MainDocumentPart

Dim myXmlPart As CustomXmlPart = mainPart.AddCustomXmlPart(CustomXmlPartType.CustomXml)

Using stream As New FileStream(fileName, FileMode.Open)
myXmlPart.FeedData(stream)
End Using
End Using
End Sub
```
### [Visual Basic](#tab/vb)
[!code-vb[](../../samples/word/add_a_new_part_to_a_package/vb/Program.vb)]

## See also

Expand Down
Loading