### Add and Get IPartEventsFeature Source: https://learn.microsoft.com/en-us/office/open-xml/general/features This example shows how to add the `IPartEventsFeature` to a part and then retrieve it to receive notifications about part events. ```csharp OpenXmlPart part = GetSomePackage(); package.AddPartEventsFeature(); var feature = part.Features.GetRequired(); ``` -------------------------------- ### Call ConvertDOCMtoDOCX Method (C#) Source: https://learn.microsoft.com/en-us/office/open-xml/word/how-to-convert-a-word-processing-document-from-the-docm-to-the-docx-file-format Example of how to call the ConvertDOCMtoDOCX method, passing the first command-line argument as the file name to convert. ```csharp ConvertDOCMtoDOCX(args[0]); ``` -------------------------------- ### Call SearchAndReplace method (C#) Source: https://learn.microsoft.com/en-us/office/open-xml/general/how-to-search-and-replace-text-in-a-document-part This is a C# example demonstrating how to call the SearchAndReplace method. It assumes the document path is passed as a command-line argument. ```csharp SearchAndReplace(args[0]); ``` -------------------------------- ### Transition Element Example (XML) Source: https://learn.microsoft.com/en-us/office/open-xml/presentation/how-to-add-transitions-between-slides-in-a-presentation An example of the XML structure for a slide transition. This specifies a slow speed, advance on click, and a 3000ms auto-advance time, using a random bar effect. ```xml ``` -------------------------------- ### Calling the ReplaceStyles Method (C#) Source: https://learn.microsoft.com/en-us/office/open-xml/word/how-to-replace-the-styles-parts-in-a-word-processing-document Example of how to call the ReplaceStyles method, passing command-line arguments as the source and target document paths. ```csharp string fromDoc = args[0]; string toDoc = args[1]; ReplaceStyles(fromDoc, toDoc); ``` -------------------------------- ### Demonstrate Feature Inheritance in Open XML SDK Source: https://learn.microsoft.com/en-us/office/open-xml/general/features This example shows how features are inherited from a package to a part. It verifies that a feature set on the package is accessible on the part, and then demonstrates setting a new feature on the part, which is no longer shared with the package. ```csharp OpenXmlPackage package = /* Create a package */; var packageFeature = new PrivateFeature(); package.Features.Set(packageFeature); var part = package.GetPartById("existingPart"); Assert.Same(part.Features.GetRequired(), package.Features.GetRequired()); part.Features.Set(new()); Assert.NotSame(part.Features.GetRequired(), package.Features.GetRequired()); private sealed class PrivateFeature { } ``` -------------------------------- ### Get Hidden Rows or Columns (Visual Basic) Source: https://learn.microsoft.com/en-us/office/open-xml/spreadsheet/how-to-retrieve-a-list-of-the-hidden-rows-or-columns-in-a-spreadsheet This Visual Basic function retrieves hidden row or column numbers from an Excel sheet. Specify 'true' for 'detectRows' to get hidden rows, or 'false' for hidden columns. Row and column numbering starts at 1. ```vb Function GetHiddenRowsOrCols(fileName As String, sheetName As String, Optional detectRows As String = "false") As List(Of UInteger) ' Given a workbook and a worksheet name, return ' either a list of hidden row numbers, or a list ' of hidden column numbers. If detectRows is true, return ' hidden rows. If detectRows is false, return hidden columns. ' Rows and columns are numbered starting with 1. Dim itemList As New List(Of UInteger)() Using document As SpreadsheetDocument = SpreadsheetDocument.Open(fileName, False) If document IsNot Nothing Then Dim wbPart As WorkbookPart = If(document.WorkbookPart, document.AddWorkbookPart()) Dim theSheet As Sheet = wbPart.Workbook.Descendants(Of Sheet)().FirstOrDefault(Function(s) s.Name = sheetName) If theSheet Is Nothing OrElse theSheet.Id Is Nothing Then Throw New ArgumentException("sheetName") Else ' The sheet does exist. Dim wsPart As WorksheetPart = TryCast(wbPart.GetPartById(theSheet.Id), WorksheetPart) Dim ws As Worksheet = wsPart?.Worksheet If ws IsNot Nothing Then If detectRows.ToLower() = "true" Then ' Retrieve hidden rows. itemList = ws.Descendants(Of Row)() _ .Where(Function(r) r?.Hidden IsNot Nothing AndAlso r.Hidden.Value) _ .Select(Function(r) r.RowIndex?.Value) _ .Cast(Of UInteger)() _ .ToList() Else ' Retrieve hidden columns. Dim cols = ws.Descendants(Of Column)().Where(Function(c) c?.Hidden IsNot Nothing AndAlso c.Hidden.Value) For Each item As Column In cols If item.Min IsNot Nothing AndAlso item.Max IsNot Nothing Then For i As UInteger = item.Min.Value To item.Max.Value itemList.Add(i) Next End If Next End If End If End If End If End Using Return itemList End Function ``` -------------------------------- ### Call AddTable Method with Sample Data in C# Source: https://learn.microsoft.com/en-us/office/open-xml/word/how-to-add-tables-to-word-processing-documents Demonstrates calling the AddTable method in C# with a specified file name and a sample 2D array of state names and abbreviations. ```csharp string fileName = args[0]; AddTable(fileName, new string[,] { { "Hawaii", "HI" }, { "California", "CA" }, { "New York", "NY" }, { "Massachusetts", "MA" } }); ``` -------------------------------- ### Create Presentation Parts (C#) Source: https://learn.microsoft.com/en-us/office/open-xml/presentation/how-to-create-a-presentation-document-by-providing-a-file-name Sets up the essential parts of a presentation, including slide masters, slide IDs, slide size, notes size, and default text styles. ```csharp static void CreatePresentationParts(PresentationPart presentationPart) { SlideMasterIdList slideMasterIdList1 = new SlideMasterIdList(new SlideMasterId() { Id = (UInt32Value)2147483648U, RelationshipId = "rId1" }); SlideIdList slideIdList1 = new SlideIdList(new SlideId() { Id = (UInt32Value)256U, RelationshipId = "rId2" }); SlideSize slideSize1 = new SlideSize() { Cx = 9144000, Cy = 6858000, Type = SlideSizeValues.Screen4x3 }; NotesSize notesSize1 = new NotesSize() { Cx = 6858000, Cy = 9144000 }; DefaultTextStyle defaultTextStyle1 = new DefaultTextStyle(); presentationPart.Presentation.Append(slideMasterIdList1, slideIdList1, slideSize1, notesSize1, defaultTextStyle1); SlidePart slidePart1; SlideLayoutPart slideLayoutPart1; SlideMasterPart slideMasterPart1; ThemePart themePart1; slidePart1 = CreateSlidePart(presentationPart); slideLayoutPart1 = CreateSlideLayoutPart(slidePart1); string slideLayoutPart1RelId = slidePart1.GetIdOfPart(slideLayoutPart1); slideMasterPart1 = CreateSlideMasterPart(slideLayoutPart1); themePart1 = CreateTheme(slideMasterPart1); slideMasterPart1.AddPart(slideLayoutPart1, "rId1"); presentationPart.AddPart(slideMasterPart1, "rId1"); presentationPart.AddPart(themePart1, "rId5"); } ``` -------------------------------- ### SpreadsheetML Workbook Example Source: https://learn.microsoft.com/en-us/office/open-xml/spreadsheet/how-to-open-a-spreadsheet-document-for-read-only-access Example of the basic document structure for a SpreadsheetML workbook, including sheets and their references. ```xml ``` -------------------------------- ### SpreadsheetML Worksheet Example Source: https://learn.microsoft.com/en-us/office/open-xml/spreadsheet/how-to-open-a-spreadsheet-document-for-read-only-access Example of the SpreadsheetML for a worksheet containing cell data, specifically a row with a single cell and its value. ```xml 100 ``` -------------------------------- ### Invoke CreateTable Method Source: https://learn.microsoft.com/en-us/office/open-xml/word/how-to-insert-a-table-into-a-word-processing-document This is the entry point for the table creation process. It takes the file path as an argument. ```C# string filePath = args[0]; CreateTable(filePath); ``` -------------------------------- ### Cell Element XML Example Source: https://learn.microsoft.com/en-us/office/open-xml/spreadsheet/how-to-insert-a-chart-into-a-spreadsheet This XML example shows the information stored for a cell, including its reference, style, formula, and calculated value. ```xml CUBEVALUE("xlextdat9 Adventure Works",C$5,$A6) 2838512.355 ``` -------------------------------- ### Row Element XML Example Source: https://learn.microsoft.com/en-us/office/open-xml/spreadsheet/how-to-insert-a-chart-into-a-spreadsheet This XML example demonstrates the structure of a row element in a spreadsheet, including cell definitions, formulas, and values. ```xml PMT(B3/12,B4,-B5) 672.68336574300008 180 360 ``` -------------------------------- ### WordprocessingML Document Structure Example Source: https://learn.microsoft.com/en-us/office/open-xml/general/how-to-remove-a-document-part-from-a-package This XML markup represents a basic WordProcessingML document containing a single paragraph with the text 'Example text.'. ```xml Example text. ``` -------------------------------- ### Color Map Example in PresentationML Source: https://learn.microsoft.com/en-us/office/open-xml/presentation/working-with-handout-master-slides This XML snippet shows an example of a color map that applies to a slide master, defining how color scheme definitions are transformed. ```xml ``` -------------------------------- ### Call AddTable Method with Sample Data in Visual Basic Source: https://learn.microsoft.com/en-us/office/open-xml/word/how-to-add-tables-to-word-processing-documents Demonstrates calling the AddTable method in Visual Basic with a specified file name and a sample 2D array of state names and abbreviations. ```vb Dim fileName As String = args(0) AddTable(fileName, New String(,) { {"Hawaii", "HI"}, {"California", "CA"}, {"New York", "NY"}, {"Massachusetts", "MA"} }) ``` -------------------------------- ### Visual Basic Implementation for Applying Theme Source: https://learn.microsoft.com/en-us/office/open-xml/presentation/how-to-apply-a-theme-to-a-presentation This Visual Basic code provides the main entry point and the theme application logic. It opens presentation documents and calls helper methods to apply the theme. ```vb Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Presentation Module MyModule Sub Main(args As String()) ApplyThemeToPresentation(args(0), args(1)) End Sub ' Apply a new theme to the presentation. Public Sub ApplyThemeToPresentation(ByVal presentationFile As String, ByVal themePresentation As String) Dim themeDocument As PresentationDocument = PresentationDocument.Open(themePresentation, False) ``` -------------------------------- ### XML Example of a Character Style Definition Source: https://learn.microsoft.com/en-us/office/open-xml/word/how-to-create-and-add-a-character-style-to-a-word-processing-document An example of an XML snippet defining a character style. It shows the 'styleId', 'aliases', and 'name' elements within a 'w:style' tag. ```xml . . ``` -------------------------------- ### Create a Table with Borders in Visual Basic Source: https://learn.microsoft.com/en-us/office/open-xml/word/how-to-insert-a-table-into-a-word-processing-document This Visual Basic code demonstrates how to initialize a table and set its border styles, applying dashed borders to all edges. ```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) ``` -------------------------------- ### Get Slide Part and Ensure Comment Part Exists (VB) Source: https://learn.microsoft.com/en-us/office/open-xml/presentation/how-to-add-a-comment-to-a-slide-in-a-presentation This VB.NET code gets the SlidePart using its relationship ID or by taking the first slide if the ID is not available. It then ensures a PowerPointCommentPart exists for the slide, adding one if necessary. ```vbnet ' Get the relationship id of the slide if it exists Dim relId As String = slideId.RelationshipId ' Use the relId to get the slide if it exists, otherwise take the first slide in the sequence Dim slidePart As SlidePart = If(relId IsNot Nothing, CType(presentationPart.GetPartById(relId), SlidePart), presentationDocument.PresentationPart.SlideParts.First()) ' If the slide part has comments parts take the first PowerPointCommentsPart ' otherwise add a new one ``` -------------------------------- ### PresentationML Presentation Element Example Source: https://learn.microsoft.com/en-us/office/open-xml/presentation/working-with-presentations This XML snippet illustrates a basic `` element, including lists for slide masters and slides, along with slide size and notes size properties. ```xml ``` -------------------------------- ### Create Media Data Part and Add Audio Reference (VB) Source: https://learn.microsoft.com/en-us/office/open-xml/presentation/how-to-add-an-audio-to-a-slide-in-a-presentation This snippet demonstrates creating a media data part for an audio file and adding it to a slide part. It also includes adding a reference to the media data part for use in the presentation. ```VB ' Create video Media Data Part (content type, extension) Dim mediaDataPart As MediaDataPart = presentationDocument.CreateMediaDataPart("video/mp4", ".mp4") ' Get the audio file and feed the stream Using mediaDataPartStream As Stream = File.OpenRead(audioFilePath) mediaDataPart.FeedData(mediaDataPartStream) End Using ' Adds a AudioReferenceRelationship to the MainDocumentPart slidePart.AddAudioReferenceRelationship(mediaDataPart, embedId) ' Adds a MediaReferenceRelationship to the SlideLayoutPart slidePart.AddMediaReferenceRelationship(mediaDataPart, mediaEmbedId) Dim nonVisualDrawingProperties As New NonVisualDrawingProperties() With { .Id = shapeId, .Name = "audio" } Dim audioFromFile As New A.AudioFromFile() With { .Link = embedId } Dim appNonVisualDrawingProperties As New ApplicationNonVisualDrawingProperties() appNonVisualDrawingProperties.Append(audioFromFile) ' Adds sample image to the slide with id to be used as reference in blip Dim imagePart As ImagePart = slidePart.AddImagePart(ImagePartType.Png, imgEmbedId) Using data As Stream = File.OpenRead(coverPicPath) imagePart.FeedData(data) End Using If slidePart.Slide.CommonSlideData.ShapeTree Is Nothing Then Throw New NullReferenceException("Presentation shape tree is empty") End If ' Getting existing shape tree object from PowerPoint Dim shapeTree As ShapeTree = slidePart.Slide.CommonSlideData.ShapeTree ' Specifies the existence of a picture within a presentation Dim picture As New Picture() Dim nonVisualPictureProperties As New NonVisualPictureProperties() Dim hyperlinkOnClick As New A.HyperlinkOnClick() With { .Id = "", .Action = "ppaction://media" } nonVisualDrawingProperties.Append(hyperlinkOnClick) Dim nonVisualPictureDrawingProperties As New NonVisualPictureDrawingProperties() Dim pictureLocks As New A.PictureLocks() With { .NoChangeAspect = True } nonVisualPictureDrawingProperties.Append(pictureLocks) Dim appNonVisualDrawingPropertiesExtensionList As New ApplicationNonVisualDrawingPropertiesExtensionList() Dim appNonVisualDrawingPropertiesExtension As New ApplicationNonVisualDrawingPropertiesExtension() With { .Uri = "{DAA4B4D4-6D71-4841-9C94-3DE7FCFB9230}" } ``` -------------------------------- ### Get Slide Part and Ensure Comment Part Exists (C#) Source: https://learn.microsoft.com/en-us/office/open-xml/presentation/how-to-add-a-comment-to-a-slide-in-a-presentation This C# code gets the SlidePart using its relationship ID or by taking the first slide if the ID is not available. It then ensures a PowerPointCommentPart exists for the slide, adding one if necessary. ```csharp // Get the relationship id of the slide if it exists string? relId = slideId.RelationshipId; // Use the relId to get the slide if it exists, otherwise take the first slide in the sequence SlidePart slidePart = relId is not null ? (SlidePart)presentationPart.GetPartById(relId) : presentationDocument.PresentationPart.SlideParts.First(); // If the slide part has comments parts take the first PowerPointCommentsPart // otherwise add a new one PowerPointCommentPart powerPointCommentPart = slidePart.commentParts.FirstOrDefault() ?? slidePart.AddNewPart(); ``` -------------------------------- ### Complete Code to Create a Word Document (C#) Source: https://learn.microsoft.com/en-us/office/open-xml/word/how-to-create-a-word-processing-document-by-providing-a-file-name This C# code provides a complete example of creating a basic Word document by specifying the file path and using the Open XML SDK to add document structure and text. ```csharp 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(); // Create the document structure and add some text. mainPart.Document = new Document(); Body body = mainPart.Document.AppendChild(new Body()); Paragraph para = body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); run.AppendChild(new Text("Create text in body - CreateWordprocessingDocument")); } } ``` -------------------------------- ### Get All External Hyperlinks in Presentation (Visual Basic) Source: https://learn.microsoft.com/en-us/office/open-xml/presentation/how-to-get-all-the-external-hyperlinks-in-a-presentation This Visual Basic function extracts all external hyperlinks from a presentation. It opens the document in read-only mode and iterates through slide parts, matching hyperlink IDs with external relationship IDs to get the URIs. ```vb ' Returns all the external hyperlinks in the slides of a presentation. Function GetAllExternalHyperlinksInPresentation(fileName As String) As IEnumerable(Of String) ' Declare a list of strings. Dim ret As New List(Of String)() ' Open the presentation file as read-only. Using document As PresentationDocument = PresentationDocument.Open(fileName, False) ' If there is no PresentationPart then there are no hyperlinks If document.PresentationPart Is Nothing Then Return ret End If ' Iterate through all the slide parts in the presentation part. For Each slidePart As SlidePart In document.PresentationPart.SlideParts Dim links As IEnumerable(Of Drawing.HyperlinkType) = slidePart.Slide.Descendants(Of Drawing.HyperlinkType)() ' Iterate through all the links in the slide part. For Each link As Drawing.HyperlinkType In links ' Iterate through all the external relationships in the slide part. For Each relation As HyperlinkRelationship In slidePart.HyperlinkRelationships ' If the relationship ID matches the link ID… If relation.Id.Equals(link.Id) Then ' Add the URI of the external relationship to the list of strings. ret.Add(relation.Uri.AbsoluteUri) End If Next Next Next End Using ' Return the list of strings. Return ret End Function ``` -------------------------------- ### Call SetPrintOrientation Method Source: https://learn.microsoft.com/en-us/office/open-xml/word/how-to-change-the-print-orientation-of-a-word-processing-document Example of how to call the `SetPrintOrientation` method, passing command-line arguments for the file name and orientation. ```csharp SetPrintOrientation(args[0], args[1]); ``` ```vb SetPrintOrientation(args(0), args(1)) ``` -------------------------------- ### Create Document Structure and Add Text (C#) Source: https://learn.microsoft.com/en-us/office/open-xml/word/how-to-create-a-word-processing-document-by-providing-a-file-name This C# code snippet shows a concise way to create the document structure and add text using the Open XML SDK. ```csharp mainPart.Document = new Document( new Body( new Paragraph( new Run( new Text("Create text in body - CreateWordprocessingDocument"))))); ``` -------------------------------- ### Create Presentation Document (C#) Source: https://learn.microsoft.com/en-us/office/open-xml/presentation/how-to-create-a-presentation-document-by-providing-a-file-name Creates a new presentation document at the specified file path. The default document type is pptx. Ensure the PresentationDocumentType is correctly specified. ```csharp static void CreatePresentation(string filepath) { // Create a presentation at a specified file path. The presentation document type is pptx, by default. using (PresentationDocument presentationDoc = PresentationDocument.Create(filepath, PresentationDocumentType.Presentation)) { PresentationPart presentationPart = presentationDoc.AddPresentationPart(); presentationPart.Presentation = new Presentation(); CreatePresentationParts(presentationPart); } } ``` -------------------------------- ### Add and Get IPackageEventsFeature Source: https://learn.microsoft.com/en-us/office/open-xml/general/features This snippet demonstrates how to add the `IPackageEventsFeature` to a package and then retrieve it to subscribe to package change notifications. ```csharp OpenXmlPackage package = GetSomePackage(); package.TryAddPackageEventsFeature(); var feature = package.Features.GetRequired(); ``` -------------------------------- ### Call SearchAndReplace method (Visual Basic) Source: https://learn.microsoft.com/en-us/office/open-xml/general/how-to-search-and-replace-text-in-a-document-part This is a Visual Basic example demonstrating how to call the SearchAndReplace method. It assumes the document path is passed as a command-line argument. ```vb SearchAndReplace(args(0)) ``` -------------------------------- ### WordprocessingML Table Structure Source: https://learn.microsoft.com/en-us/office/open-xml/word/working-with-wordprocessingml-tables This is the WordprocessingML XML output generated by the preceding C# and VB code examples when inserting a table. ```xml 1 2 3 ``` -------------------------------- ### Complete Code to Create a Word Document (Visual Basic) Source: https://learn.microsoft.com/en-us/office/open-xml/word/how-to-create-a-word-processing-document-by-providing-a-file-name This Visual Basic code provides a complete example of creating a basic Word document by specifying the file path and using the Open XML SDK to add document structure and text. ```vb Public Sub CreateWordprocessingDocument(ByVal filepath As String) ' Create a document by supplying the filepath. Using wordDocument As WordprocessingDocument = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document) ' Add a main document part. Dim mainPart As MainDocumentPart = wordDocument.AddMainDocumentPart() ' Create the document structure and add some text. mainPart.Document = New Document() Dim body As Body = mainPart.Document.AppendChild(New Body()) Dim para As Paragraph = body.AppendChild(New Paragraph()) Dim run As Run = para.AppendChild(New Run()) run.AppendChild(New Text("Create text in body - CreateWordprocessingDocument")) End Using End Sub ``` -------------------------------- ### Call RemoveHeadersAndFooters Method (VB.NET) Source: https://learn.microsoft.com/en-us/office/open-xml/word/how-to-remove-the-headers-and-footers-from-a-word-processing-document Example of how to call the RemoveHeadersAndFooters method in VB.NET, passing the filename obtained from command-line arguments. ```vbnet Dim filename As String = args(0) RemoveHeadersAndFooters(filename) ``` -------------------------------- ### Call RemoveHeadersAndFooters Method (C#) Source: https://learn.microsoft.com/en-us/office/open-xml/word/how-to-remove-the-headers-and-footers-from-a-word-processing-document Example of how to call the RemoveHeadersAndFooters method in C#, passing the filename obtained from command-line arguments. ```csharp string filename = args[0]; RemoveHeadersAndFooters(filename); ``` -------------------------------- ### Create Document Structure and Add Text (Visual Basic) Source: https://learn.microsoft.com/en-us/office/open-xml/word/how-to-create-a-word-processing-document-by-providing-a-file-name This Visual Basic code snippet shows a concise way to create the document structure and add text using the Open XML SDK. ```vb mainPart.Document = New Document(New Body(New Paragraph(New Run(New Text("Create text in body - CreateWordprocessingDocument"))))) ``` -------------------------------- ### Get All Text in a Slide (VB.NET) Source: https://learn.microsoft.com/en-us/office/open-xml/presentation/how-to-get-all-the-text-in-a-slide-in-a-presentation Opens a presentation file and calls an overloaded method to retrieve all text from a specified slide. ```vbnet ' Get all the text in a slide. Public Shared Function GetAllTextInSlide(presentationFile As String, slideIndex As Integer) As String() ' Open the presentation as read-only. Using presentationDocument As PresentationDocument = PresentationDocument.Open(presentationFile, False) ' Pass the presentation and the slide index ' to the next GetAllTextInSlide method, and ' then return the array of strings it returns. Return GetAllTextInSlide(presentationDocument, slideIndex) End Using End Function ``` -------------------------------- ### Add Video and Placeholder Image in C# Source: https://learn.microsoft.com/en-us/office/open-xml/presentation/how-to-add-a-video-to-a-slide-in-a-presentation Creates a media data part for the video, adds video and media relationships to the slide, and inserts a placeholder image. Requires file paths for the video and cover image, and embed IDs. ```C# // Create video Media Data Part (content type, extension) MediaDataPart mediaDataPart = presentationDocument.CreateMediaDataPart("video/mp4", ".mp4"); //Get the video file and feed the stream using (Stream mediaDataPartStream = File.OpenRead(videoFilePath)) { mediaDataPart.FeedData(mediaDataPartStream); } //Adds a VideoReferenceRelationship to the MainDocumentPart slidePart.AddVideoReferenceRelationship(mediaDataPart, embedId); //Adds a MediaReferenceRelationship to the SlideLayoutPart slidePart.AddMediaReferenceRelationship(mediaDataPart, mediaEmbedId); NonVisualDrawingProperties nonVisualDrawingProperties = new NonVisualDrawingProperties() { Id = shapeId, Name = "video" }; A.VideoFromFile videoFromFile = new A.VideoFromFile() { Link = embedId }; ApplicationNonVisualDrawingProperties appNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties(); appNonVisualDrawingProperties.Append(videoFromFile); //adds sample image to the slide with id to be used as reference in blip ImagePart imagePart = slidePart.AddImagePart(ImagePartType.Png, imgEmbedId); using (Stream data = File.OpenRead(coverPicPath)) { imagePart.FeedData(data); } if (slidePart!.Slide!.CommonSlideData!.ShapeTree == null) { throw new NullReferenceException("Presentation shape tree is empty"); } //Getting existing shape tree object from PowerPoint ShapeTree shapeTree = slidePart.Slide.CommonSlideData.ShapeTree; // specifies the existence of a picture within a presentation. // It can have non-visual properties, a picture fill as well as shape properties attached to it. Picture picture = new Picture(); NonVisualPictureProperties nonVisualPictureProperties = new NonVisualPictureProperties(); A.HyperlinkOnClick hyperlinkOnClick = new A.HyperlinkOnClick() { Id = "", Action = "ppaction://media" }; nonVisualDrawingProperties.Append(hyperlinkOnClick); NonVisualPictureDrawingProperties nonVisualPictureDrawingProperties = new NonVisualPictureDrawingProperties(); A.PictureLocks pictureLocks = new A.PictureLocks() { NoChangeAspect = true }; nonVisualPictureDrawingProperties.Append(pictureLocks); ApplicationNonVisualDrawingPropertiesExtensionList appNonVisualDrawingPropertiesExtensionList = new ApplicationNonVisualDrawingPropertiesExtensionList(); ``` -------------------------------- ### Get All Text in a Slide (C#) Source: https://learn.microsoft.com/en-us/office/open-xml/presentation/how-to-get-all-the-text-in-a-slide-in-a-presentation Opens a presentation file and calls an overloaded method to retrieve all text from a specified slide. ```csharp public static string[] GetAllTextInSlide(string presentationFile, int slideIndex) { // Open the presentation as read-only. using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, false)) { // Pass the presentation and the slide index // to the next GetAllTextInSlide method, and // then return the array of strings it returns. return GetAllTextInSlide(presentationDocument, slideIndex); } } ``` -------------------------------- ### Open Presentation Documents for Theme Application (C#) Source: https://learn.microsoft.com/en-us/office/open-xml/presentation/how-to-apply-a-theme-to-a-presentation Opens the source and target presentation documents. The source is opened for read-only access, and the target for read/write access. Ensure the PresentationDocument class is imported. ```csharp using (PresentationDocument themeDocument = PresentationDocument.Open(themePresentation, false)) using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, true)) { } ``` -------------------------------- ### Invoke CreateTable Method (Visual Basic) Source: https://learn.microsoft.com/en-us/office/open-xml/word/how-to-insert-a-table-into-a-word-processing-document This is the entry point for the table creation process in Visual Basic. It takes the file path as an argument. ```VB Dim filePath As String = args(0) CreateTable(filePath) ``` -------------------------------- ### Add and Get IPartRootEventsFeature Source: https://learn.microsoft.com/en-us/office/open-xml/general/features This snippet illustrates adding the `IPartRootEventsFeature` to a part and then retrieving it to monitor modifications to the part's root. ```csharp OpenXmlPart part = GetSomePart(); part.AddPartRootEventsFeature(); var feature = part.Features.GetRequired(); ``` -------------------------------- ### Call ConvertDOCMtoDOCX Method (Visual Basic) Source: https://learn.microsoft.com/en-us/office/open-xml/word/how-to-convert-a-word-processing-document-from-the-docm-to-the-docx-file-format Example of how to call the ConvertDOCMtoDOCX method in Visual Basic, passing the first command-line argument as the file name to convert. ```vb ConvertDOCMtoDOCX(args(0)) ``` -------------------------------- ### Open Presentation and Get/Add SlidePart Source: https://learn.microsoft.com/en-us/office/open-xml/presentation/working-with-notes-slides Opens a presentation document and retrieves the first slide part. If no slide part exists, it inserts a new one. Requires the presentation document to exist. ```C# using (PresentationDocument presentationDocument = PresentationDocument.Open(pptxPath, true) ?? throw new Exception("Presentation Document does not exist")) { // Get the first slide in the presentation or use the InsertNewSlide.InsertNewSlideIntoPresentation helper method to insert a new slide. SlidePart slidePart = presentationDocument.PresentationPart?.SlideParts.FirstOrDefault() ?? InsertNewSlideNS.InsertNewSlide(presentationDocument, 1, "my new slide"); // Add a new NoteSlidePart if one does not already exist NotesSlidePart notesSlidePart = slidePart.NotesSlidePart ?? slidePart.AddNewPart(); ``` ```VB Using presentationDocument As PresentationDocument = PresentationDocument.Open(pptxPath, True) If presentationDocument Is Nothing Then Throw New Exception("Presentation Document does not exist") ' Get the first slide in the presentation or use the InsertNewSlide.InsertNewSlideIntoPresentation helper method to insert a new slide. Dim slidePart As SlidePart = If(presentationDocument.PresentationPart?.SlideParts.FirstOrDefault(), InsertNewSlide.InsertNewSlide(presentationDocument, 1, "my new slide")) ' Add a new NoteSlidePart if one does not already exist Dim notesSlidePart As NotesSlidePart = If(slidePart.NotesSlidePart, slidePart.AddNewPart(Of NotesSlidePart)()) ``` -------------------------------- ### Complete Header Replacement Implementation (C#) Source: https://learn.microsoft.com/en-us/office/open-xml/word/how-to-replace-the-header-in-a-word-processing-document This is the complete C# implementation for the AddHeaderFromTo method. It opens both source and target documents, deletes the existing header in the target, creates a new header part, copies the header data from the source, and updates the section properties to reference the new header. Ensure the Open XML SDK is referenced. ```csharp using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System; using System.Collections.Generic; using System.Linq; static void AddHeaderFromTo(string fromFile, string toFile) { // Replace header in target document with header of source document. using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(toFile, true)) using (WordprocessingDocument wdDocSource = WordprocessingDocument.Open(fromFile, true)) { if (wdDocSource.MainDocumentPart is null || wdDocSource.MainDocumentPart.HeaderParts is null) { throw new ArgumentNullException("MainDocumentPart and/or HeaderParts is null."); } if (wdDoc.MainDocumentPart is null) { throw new ArgumentNullException("MainDocumentPart is null."); } MainDocumentPart mainPart = wdDoc.MainDocumentPart; // Delete the existing header part. mainPart.DeleteParts(mainPart.HeaderParts); // Create a new header part. DocumentFormat.OpenXml.Packaging.HeaderPart headerPart = mainPart.AddNewPart(); // Get Id of the headerPart. string rId = mainPart.GetIdOfPart(headerPart); // Feed target headerPart with source headerPart. DocumentFormat.OpenXml.Packaging.HeaderPart? firstHeader = wdDocSource.MainDocumentPart.HeaderParts.FirstOrDefault(); wdDocSource.MainDocumentPart.HeaderParts.FirstOrDefault(); if (firstHeader is not null) { headerPart.FeedData(firstHeader.GetStream()); } if (mainPart.Document.Body is null) { throw new ArgumentNullException("Body is null."); } // Get SectionProperties and Replace HeaderReference with new Id. IEnumerable sectPrs = mainPart.Document.Body.Elements(); foreach (var sectPr in sectPrs) { // Delete existing references to headers. sectPr.RemoveAllChildren(); // Create the new header reference node. sectPr.PrependChild(new HeaderReference() { Id = rId }); } } } ``` -------------------------------- ### Slide Master Part Root Element Source: https://learn.microsoft.com/en-us/office/open-xml/presentation/structure-of-a-presentationml-document The root element for a Slide Master part is sldMaster. This example shows its basic structure. ```xml ``` -------------------------------- ### Apply Theme to Presentation (C#) Source: https://learn.microsoft.com/en-us/office/open-xml/presentation/how-to-apply-a-theme-to-a-presentation Opens two presentation documents and passes them to a method to apply a theme. Use this overload when you have file paths for both the presentation and the theme. ```csharp // Apply a new theme to the presentation. static void ApplyThemeToPresentation(string presentationFile, string themePresentation) { using (PresentationDocument themeDocument = PresentationDocument.Open(themePresentation, false)) using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, true)) { ApplyThemeToPresentationDocument(presentationDocument, themeDocument); } } ``` -------------------------------- ### Presentation Properties Part Root Element Source: https://learn.microsoft.com/en-us/office/open-xml/presentation/structure-of-a-presentationml-document The root element for the Presentation Properties part is presentationPr. This example shows its basic structure. ```xml ``` -------------------------------- ### Get Worksheet from SpreadsheetDocument Source: https://learn.microsoft.com/en-us/office/open-xml/spreadsheet/how-to-merge-two-adjacent-cells-in-a-spreadsheet Retrieves a specific worksheet from a SpreadsheetDocument based on its name. Ensures the workbook part exists, adding it if necessary. ```vb ' Given a SpreadsheetDocument and a worksheet name, get the specified worksheet. Function GetWorksheet(document As SpreadsheetDocument, worksheetName As String) As Worksheet Dim workbookPart As WorkbookPart = If(document.WorkbookPart, document.AddWorkbookPart()) Dim sheets As IEnumerable(Of Sheet) = workbookPart.Workbook.Descendants(Of Sheet)().Where(Function(s) s.Name = worksheetName) Dim id As String = sheets.First().Id Dim worksheetPart As WorksheetPart = If(id IsNot Nothing, CType(workbookPart.GetPartById(id), WorksheetPart), Nothing) Return If(worksheetPart IsNot Nothing, worksheetPart.Worksheet, Nothing) End Function ``` -------------------------------- ### Get Slide Count from PresentationDocument (C#) Source: https://learn.microsoft.com/en-us/office/open-xml/presentation/how-to-delete-a-slide-from-a-presentation Retrieves the slide count by accessing the PresentationPart and its SlideParts. Handles null checks for safety. ```csharp if (presentationDocument is null) { throw new ArgumentNullException("presentationDocument"); } int slidesCount = 0; // Get the presentation part of document. PresentationPart? presentationPart = presentationDocument.PresentationPart; // Get the slide count from the SlideParts. if (presentationPart is not null) { slidesCount = presentationPart.SlideParts.Count(); } // Return the slide count to the previous method. return slidesCount; ``` -------------------------------- ### Add Audio to a Slide using Open XML SDK (C#) Source: https://learn.microsoft.com/en-us/office/open-xml/presentation/how-to-add-an-audio-to-a-slide-in-a-presentation This code adds an audio file to the last slide of a presentation. It creates a MediaDataPart for the audio, establishes relationships, and adds a picture to serve as the audio's visual representation on the slide. Ensure the audio and cover image files exist at the specified paths. ```C# Module Program Sub Main(args As String()) AddAudio(args(0), args(1), args(2)) End Sub Sub AddAudio(filePath As String, audioFilePath As String, coverPicPath As String) Dim imgEmbedId As String = "rId4" Dim embedId As String = "rId3" Dim mediaEmbedId As String = "rId2" Dim shapeId As UInt32Value = 5 Using presentationDocument As PresentationDocument = PresentationDocument.Open(filePath, True) If presentationDocument.PresentationPart Is Nothing OrElse presentationDocument.PresentationPart.Presentation.SlideIdList Is Nothing Then Throw New NullReferenceException("Presentation Part is empty or there are no slides in it") End If ' Get presentation part Dim presentationPart As PresentationPart = presentationDocument.PresentationPart ' Get slides ids Dim slidesIds As OpenXmlElementList = presentationPart.Presentation.SlideIdList.ChildElements ' Get relationshipId of the last slide Dim audioSldRelationshipId As String = CType(slidesIds(slidesIds.ToArray().Length - 1), SlideId).RelationshipId If audioSldRelationshipId Is Nothing Then Throw New NullReferenceException("Slide id not found") End If ' Get slide part by relationshipID Dim slidePart As SlidePart = CType(presentationPart.GetPartById(audioSldRelationshipId), SlidePart) ' Create video Media Data Part (content type, extension) Dim mediaDataPart As MediaDataPart = presentationDocument.CreateMediaDataPart("video/mp4", ".mp4") ' Get the audio file and feed the stream Using mediaDataPartStream As Stream = File.OpenRead(audioFilePath) mediaDataPart.FeedData(mediaDataPartStream) End Using ' Adds a AudioReferenceRelationship to the MainDocumentPart slidePart.AddAudioReferenceRelationship(mediaDataPart, embedId) ' Adds a MediaReferenceRelationship to the SlideLayoutPart slidePart.AddMediaReferenceRelationship(mediaDataPart, mediaEmbedId) Dim nonVisualDrawingProperties As New NonVisualDrawingProperties() With { .Id = shapeId, .Name = "audio" } Dim audioFromFile As New A.AudioFromFile() With { .Link = embedId } Dim appNonVisualDrawingProperties As New ApplicationNonVisualDrawingProperties() appNonVisualDrawingProperties.Append(audioFromFile) ' Adds sample image to the slide with id to be used as reference in blip Dim imagePart As ImagePart = slidePart.AddImagePart(ImagePartType.Png, imgEmbedId) Using data As Stream = File.OpenRead(coverPicPath) imagePart.FeedData(data) End Using If slidePart.Slide.CommonSlideData.ShapeTree Is Nothing Then Throw New NullReferenceException("Presentation shape tree is empty") End If ' Getting existing shape tree object from PowerPoint Dim shapeTree As ShapeTree = slidePart.Slide.CommonSlideData.ShapeTree ' Specifies the existence of a picture within a presentation Dim picture As New Picture() Dim nonVisualPictureProperties As New NonVisualPictureProperties() Dim hyperlinkOnClick As New A.HyperlinkOnClick() With { .Id = "", .Action = "ppaction://media" } nonVisualDrawingProperties.Append(hyperlinkOnClick) Dim nonVisualPictureDrawingProperties As New NonVisualPictureDrawingProperties() Dim pictureLocks As New A.PictureLocks() With { .NoChangeAspect = True } End Using End Sub End Module ``` -------------------------------- ### Opening Presentation Document (C#) Source: https://learn.microsoft.com/en-us/office/open-xml/presentation/how-to-retrieve-the-number-of-slides-in-a-presentation-document Opens a presentation document for read-only access using the Open XML SDK in C#. This is the initial step before accessing presentation parts. ```csharp using (PresentationDocument doc = PresentationDocument.Open(fileName, false)) { if (doc.PresentationPart is not null) { // Get the presentation part of the document. PresentationPart presentationPart = doc.PresentationPart; ```