### Call Sample Method to Add Style (C#) Source: https://github.com/officedev/open-xml-docs/blob/main/docs/word/how-to-create-and-add-a-paragraph-style-to-a-word-processing-document.md This example shows how to open a Word document, get a reference to the style definitions part, and then call the CreateAndAddParagraphStyle method to add a new paragraph style. It also demonstrates applying the new style to a paragraph. ```csharp using (WordprocessingDocument wordDoc = WordprocessingDocument.Open("Sample.docx", true)) { // Get the main document part. MainDocumentPart mainPart = wordDoc.MainDocumentPart; // Create a new paragraph style. string styleid = "OverdueAmountPara"; string stylename = "Overdue Amount Para"; string stylealiases = "Late Due, Late Amount"; // Get the style definitions part, or create it if it does not exist. StyleDefinitionsPart stylePart; if (mainPart.StyleDefinitionsPart == null) { stylePart = mainPart.AddNewPart(); } else { stylePart = mainPart.StyleDefinitionsPart; } // Create and add the new paragraph style. CreateAndAddParagraphStyle(stylePart, styleid, stylename, stylealiases); // Add a paragraph of text and apply the new style. Paragraph para = new Paragraph(); para.ParagraphProperties = new ParagraphProperties(); para.ParagraphProperties.ParagraphStyleId = new ParagraphStyleId() { Val = styleid }; Run run = new Run(); Text t = new Text("This is a paragraph with the Overdue Amount Para style."); run.Append(t); para.Append(run); mainPart.Document.Body.Append(para); wordDoc.Save(); } ``` -------------------------------- ### Call Sample Method to Add Style (Visual Basic) Source: https://github.com/officedev/open-xml-docs/blob/main/docs/word/how-to-create-and-add-a-paragraph-style-to-a-word-processing-document.md This example shows how to open a Word document, get a reference to the style definitions part, and then call the CreateAndAddParagraphStyle method to add a new paragraph style. It also demonstrates applying the new style to a paragraph. ```vb Using wordDoc As WordprocessingDocument = WordprocessingDocument.Open("Sample.docx", True) ' Get the main document part. Dim mainPart As MainDocumentPart = wordDoc.MainDocumentPart ' Create a new paragraph style. Dim styleid As String = "OverdueAmountPara" Dim stylename As String = "Overdue Amount Para" Dim stylealiases As String = "Late Due, Late Amount" ' Get the style definitions part, or create it if it does not exist. Dim stylePart As StyleDefinitionsPart If mainPart.StyleDefinitionsPart Is Nothing Then stylePart = mainPart.AddNewPart(Of StyleDefinitionsPart)() Else stylePart = mainPart.StyleDefinitionsPart End If ' Create and add the new paragraph style. CreateAndAddParagraphStyle(stylePart, styleid, stylename, stylealiases) ' Add a paragraph of text and apply the new style. Dim para As New Paragraph() para.ParagraphProperties = New ParagraphProperties() para.ParagraphProperties.ParagraphStyleId = New ParagraphStyleId() With { .Val = styleid } Dim run As New Run() Dim t As New Text("This is a paragraph with the Overdue Amount Para style.") run.Append(t) para.Append(run) mainPart.Document.Body.Append(para) wordDoc.Save() End Using ``` -------------------------------- ### Add and Get IPartEventsFeature in Open XML SDK Source: https://github.com/officedev/open-xml-docs/blob/main/docs/general/features.md This example shows how to add the IPartEventsFeature to a part or package and then retrieve it to receive event notifications related to part changes. ```csharp OpenXmlPart part = GetSomePackage(); package.AddPartEventsFeature(); var feature = part.Features.GetRequired(); ``` -------------------------------- ### Full Sample Code - C# Source: https://github.com/officedev/open-xml-docs/blob/main/docs/presentation/how-to-open-a-presentation-document-for-read-only-access.md The complete C# code listing for the presentation document read-only access example. ```csharp [!code-csharp[](../../samples/presentation/open_for_read_only_access/cs/Program.cs#snippet0)] ``` -------------------------------- ### Complete code example for adding document parts Source: https://github.com/officedev/open-xml-docs/blob/main/docs/general/how-to-add-a-new-document-part-that-receives-a-relationship-id-to-a-package.md This is a complete code example demonstrating how to add various document parts, including custom XML, to an Open XML WordprocessingDocument. It covers initialization, adding core parts, and adding specialized parts like digital signature origin, extended properties, and thumbnails. ```C# using System; using System.IO; using System.Xml.Linq; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; namespace AddNewPartRelationshipId { class Program { static void Main(string[] args) { string filepath = "C:\\Users\\Public\\Documents\\MyNewDoc.docx"; AddParts(filepath); } public static void AddParts(string filepath) { using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document)) { MainDocumentPart mainPart = wordDoc.AddMainDocumentPart(); mainPart.PutXDocument(new XDocument(new XElement(XName.Get("document", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"), new XElement(XName.Get("body", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"))))); CustomFilePropertiesPart customFilePropertiesPart = wordDoc.AddCustomFilePropertiesPart(); customFilePropertiesPart.PutXDocument(new XDocument(new XElement(XName.Get("Properties", "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties")))); CoreFilePropertiesPart coreFilePropertiesPart = wordDoc.AddCoreFilePropertiesPart(); coreFilePropertiesPart.PutXDocument(new XDocument(new XElement(XName.Get("coreProperties", "http://schemas.openxmlformats.org/package/2006/metadata/core-properties")))); DigitalSignatureOriginPart digitalSignatureOriginPart = wordDoc.AddDigitalSignatureOriginPart(); digitalSignatureOriginPart.PutXDocument(new XDocument(new XElement(XName.Get("Relationships", "http://schemas.openxmlformats.org/package/2006/relationships")))); ExtendedFilePropertiesPart extendedFilePropertiesPart = wordDoc.AddExtendedFilePropertiesPart(); extendedFilePropertiesPart.PutXDocument(new XDocument(new XElement(XName.Get("Properties", "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties")))); ThumbnailPart thumbnailPart = wordDoc.AddThumbnailPart(); thumbnailPart.ChangeImage(System.Drawing.Imaging.ImageFormat.Png); } } } } ``` -------------------------------- ### Complete code example for adding document parts (Visual Basic) Source: https://github.com/officedev/open-xml-docs/blob/main/docs/general/how-to-add-a-new-document-part-that-receives-a-relationship-id-to-a-package.md This is a complete code example demonstrating how to add various document parts, including custom XML, to an Open XML WordprocessingDocument. It covers initialization, adding core parts, and adding specialized parts like digital signature origin, extended properties, and thumbnails. ```Visual Basic Imports System Imports System.IO Imports System.Xml.Linq Imports DocumentFormat.OpenXml Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Wordprocessing Namespace AddNewPartRelationshipId Friend Class Program Shared Sub Main(args As String()) Dim filepath As String = "C:\\Users\\Public\\Documents\\MyNewDoc.docx" AddParts(filepath) End Sub Public Shared Sub AddParts(filepath As String) Using wordDoc As WordprocessingDocument = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document) Dim mainPart As MainDocumentPart = wordDoc.AddMainDocumentPart() mainPart.PutXDocument(New XDocument(New XElement(XName.Get("document", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"), New XElement(XName.Get("body", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"))))) Dim customFilePropertiesPart As CustomFilePropertiesPart = wordDoc.AddCustomFilePropertiesPart() customFilePropertiesPart.PutXDocument(New XDocument(New XElement(XName.Get("Properties", "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties")))) Dim coreFilePropertiesPart As CoreFilePropertiesPart = wordDoc.AddCoreFilePropertiesPart() coreFilePropertiesPart.PutXDocument(New XDocument(New XElement(XName.Get("coreProperties", "http://schemas.openxmlformats.org/package/2006/metadata/core-properties")))) Dim digitalSignatureOriginPart As DigitalSignatureOriginPart = wordDoc.AddDigitalSignatureOriginPart() digitalSignatureOriginPart.PutXDocument(New XDocument(New XElement(XName.Get("Relationships", "http://schemas.openxmlformats.org/package/2006/relationships")))) Dim extendedFilePropertiesPart As ExtendedFilePropertiesPart = wordDoc.AddExtendedFilePropertiesPart() extendedFilePropertiesPart.PutXDocument(New XDocument(New XElement(XName.Get("Properties", "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties")))) Dim thumbnailPart As ThumbnailPart = wordDoc.AddThumbnailPart() thumbnailPart.ChangeImage(System.Drawing.Imaging.ImageFormat.Png) End Using End Sub End Class End Namespace ``` -------------------------------- ### Complete code example to remove a document part Source: https://github.com/officedev/open-xml-docs/blob/main/docs/general/how-to-remove-a-document-part-from-a-package.md This is the complete code example in C# and Visual Basic that demonstrates how to open a Wordprocessing document and remove its Document Settings part. ```C# using System; using DocumentFormat.OpenXml.Packaging; namespace RemoveDocumentPart { class Program { static void Main(string[] args) { // The file path for the Wordprocessing document. string filePath = "C:\\Users\\Public\\Documents\\MyDocument.docx"; try { // Open the document in read/write mode. using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(filePath, true)) { // Get the main document part. MainDocumentPart mainPart = wordDocument.MainDocumentPart; // Get the DocumentSettingsPart. DocumentSettingsPart settingsPart = mainPart.DocumentSettingsPart; // Check if the settings part exists and delete it. if (settingsPart != null) { settingsPart.DeletePart(); Console.WriteLine("Document Settings part removed successfully."); } else { Console.WriteLine("Document Settings part not found."); } } } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } } } } ``` ```Visual Basic Imports System Imports DocumentFormat.OpenXml.Packaging Module Module1 Sub Main() ' The file path for the Wordprocessing document. Dim filePath As String = "C:\\Users\\Public\\Documents\\MyDocument.docx" Try ' Open the document in read/write mode. Using wordDocument As WordprocessingDocument = WordprocessingDocument.Open(filePath, True) ' Get the main document part. Dim mainPart As MainDocumentPart = wordDocument.MainDocumentPart ' Get the DocumentSettingsPart. Dim settingsPart As DocumentSettingsPart = mainPart.DocumentSettingsPart ' Check if the settings part exists and delete it. If settingsPart IsNot Nothing Then settingsPart.DeletePart() Console.WriteLine("Document Settings part removed successfully.") Else Console.WriteLine("Document Settings part not found.") End If End Using Catch ex As Exception Console.WriteLine("Error: " & ex.Message) End Try End Sub End Module ``` -------------------------------- ### Full Sample Code - Visual Basic Source: https://github.com/officedev/open-xml-docs/blob/main/docs/presentation/how-to-open-a-presentation-document-for-read-only-access.md The complete Visual Basic code listing for the presentation document read-only access example. ```vb [!code-vb[](../../samples/presentation/open_for_read_only_access/vb/Program.vb#snippet0)] ``` -------------------------------- ### Open Presentation and Get/Add SlidePart Source: https://github.com/officedev/open-xml-docs/blob/main/docs/presentation/working-with-notes-slides.md Opens a presentation using Presentation.Open and retrieves or adds the first SlidePart. This is a common setup step for working with presentation slides. ```csharp using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Presentation; // Open a presentation document. using (PresentationDocument presentationDocument = PresentationDocument.Open("D:\\sample.pptx", true)) { // Get the presentation part of the presentation document. PresentationPart presentationPart = presentationDocument.PresentationPart; // Get the first slide. SlidePart slidePart = presentationPart.SlideParts.FirstOrDefault(); // If there is no slide part, add one. if (slidePart == null) { slidePart = presentationPart.AddNewPart(); // Add a blank slide to the presentation. // The slide content is defined by the SlideLayoutPart. // For this example, we are using the first slide layout. // You can change this to any other slide layout. string relationshipType; if (presentationPart.SlideMasterParts.Count() > 0) { // Get the first slide master part. SlideMasterPart slideMasterPart = presentationPart.SlideMasterParts.FirstOrDefault(); // Get the first slide layout part. SlideLayoutPart slideLayoutPart = slideMasterPart.SlideLayoutParts.FirstOrDefault(); relationshipType = slideLayoutPart.RelationshipType; } else { // If there is no slide master part, add one. SlideMasterPart slideMasterPart = presentationPart.AddNewPart(); // Add a default slide layout part. SlideLayoutPart slideLayoutPart = slideMasterPart.AddNewPart(); relationshipType = slideLayoutPart.RelationshipType; // Add a default slide master part. presentationPart.AddPart(slideMasterPart); } slidePart.AddPart(new SlideLayoutPart(), relationshipType); // Add the slide to the presentation. presentationPart.AddPart(slidePart, relationshipType); } // Now you can work with the slide part. // For example, you can get the NotesSlidePart associated with the slide. NotesSlidePart notesSlidePart = slidePart.NotesSlidePart; // If there is no notes slide part, add one. if (notesSlidePart == null) { notesSlidePart = slidePart.AddNewPart(); // Add a default notes slide to the presentation. // The notes slide content is defined by the NotesMaster. // For this example, we are using the first notes master. // You can change this to any other notes master. string notesRelationshipType; if (presentationPart.NotesMasterParts.Count() > 0) { // Get the first notes master part. NotesMasterPart notesMasterPart = presentationPart.NotesMasterParts.FirstOrDefault(); notesRelationshipType = notesMasterPart.RelationshipType; } else { // If there is no notes master part, add one. NotesMasterPart notesMasterPart = presentationPart.AddNewPart(); // Add a default notes master part. presentationPart.AddPart(notesMasterPart); notesRelationshipType = notesMasterPart.RelationshipType; } notesSlidePart.AddPart(new NotesMasterPart(), notesRelationshipType); // Add the notes slide to the presentation. slidePart.AddPart(notesSlidePart, notesRelationshipType); } // Now you can work with the notes slide part. // For example, you can get the NotesSlide associated with the notes slide part. NotesSlide notesSlide = notesSlidePart.NotesSlide; // Add a common slide data element to the notes slide. CommonSlideData commonSlideData = notesSlide.CommonSlideData ?? notesSlide.AppendChild(new CommonSlideData()); // Add a color map override element to the notes slide. ColorMapOverride colorMapOverride = commonSlideData.ColorMapOverride ?? commonSlideData.AppendChild(new ColorMapOverride()); // Add a shape tree element to the notes slide. ShapeTree shapeTree = commonSlideData.ShapeTree ?? commonSlideData.AppendChild(new ShapeTree()); // Add a shape element to the notes slide. Shape shape = shapeTree.AppendChild(new Shape()); // Save the changes to the presentation document. presentationDocument.Save(); } ``` -------------------------------- ### Get worksheet information from an Open XML package (C#) Source: https://github.com/officedev/open-xml-docs/blob/main/docs/spreadsheet/how-to-get-worksheet-information-from-a-package.md Instantiate the Sheets class after opening the file for read-only access. This code snippet is part of a larger example for retrieving worksheet information. ```csharp using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filepath, false)) { // Get the presentation part of the presentation document. SpreadsheetPart spreadsheetPart = spreadsheetDocument.SpreadsheetPart; // Get the list of the sheets in the workbook. Sheets sheets = spreadsheetPart.WorkbookPart.GetPartsInclusive().Select(w => spreadsheetDocument.WorkbookPart.Workbook.Descendants().Where(s => spreadsheetDocument.WorkbookPart.GetIdOfPart(w) == s.Id.Value).FirstOrDefault()).Where(s => s != null).ToList(); // Iterate through the sheets and display information. foreach (Sheet sheet in sheets) { Console.WriteLine("Sheet Name: {0}", sheet.Name); Console.WriteLine("Sheet ID: {0}", sheet.Id); } } ``` -------------------------------- ### Call the sample method to create and apply a character style (C#) Source: https://github.com/officedev/open-xml-docs/blob/main/docs/word/how-to-create-and-add-a-character-style-to-a-word-processing-document.md This example shows how to open a document, retrieve its style definitions part, and then call the CreateAndAddCharacterStyle method. It also demonstrates applying the created style to a text run. ```csharp public static void CallCreateAndAddCharacterStyle(string documentPath) { // Create a character style and add it to the document. CreateAndAddCharacterStyle(documentPath, "OverdueAmountChar", "Overdue Amount Char", "Late Due, Late Amount"); using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(documentPath, true)) { MainDocumentPart mainPart = wordDoc.MainDocumentPart; Document document = mainPart.Document; Body body = document.Body; // Create a paragraph. Paragraph para = new Paragraph(); // Create three runs of text. Run run1 = new Run(); Text text1 = new Text("This is normal text. "); run1.Append(text1); Run run2 = new Run(); Text text2 = new Text("This text will be styled. "); // Apply the character style to the second run. run2.Append(text1); run2.RunProperties = new RunProperties(); run2.RunProperties.Append(new RunStyle() { Val = "OverdueAmountChar" }); run2.Append(text2); Run run3 = new Run(); Text text3 = new Text("This is normal text again."); run3.Append(text3); // Add the runs to the paragraph. para.Append(run1); para.Append(run2); para.Append(run3); // Add the paragraph to the document body. body.Append(para); // Save changes to the document. document.Save(); } } ``` -------------------------------- ### Call the sample method to create and apply a character style (Visual Basic) Source: https://github.com/officedev/open-xml-docs/blob/main/docs/word/how-to-create-and-add-a-character-style-to-a-word-processing-document.md This example shows how to open a document, retrieve its style definitions part, and then call the CreateAndAddCharacterStyle method. It also demonstrates applying the created style to a text run. ```vb Public Shared Sub CallCreateAndAddCharacterStyle(ByVal documentPath As String) ' Create a character style and add it to the document. CreateAndAddCharacterStyle(documentPath, "OverdueAmountChar", "Overdue Amount Char", "Late Due, Late Amount") Using wordDoc As WordprocessingDocument = WordprocessingDocument.Open(documentPath, True) Dim mainPart As MainDocumentPart = wordDoc.MainDocumentPart Dim document As Document = mainPart.Document Dim body As Body = document.Body ' Create a paragraph. Dim para As New Paragraph() ' Create three runs of text. Dim run1 As New Run() Dim text1 As New Text("This is normal text. ") run1.Append(text1) Dim run2 As New Run() Dim text2 As New Text("This text will be styled. ") ' Apply the character style to the second run. run2.Append(text1) run2.RunProperties = New RunProperties() run2.RunProperties.Append(New RunStyle() With { .Val = "OverdueAmountChar" }) run2.Append(text2) Dim run3 As New Run() Dim text3 As New Text("This is normal text again.") run3.Append(text3) ' Add the runs to the paragraph. para.Append(run1) para.Append(run2) para.Append(run3) ' Add the paragraph to the document body. body.Append(para) ' Save changes to the document. document.Save() End Using End Sub ``` -------------------------------- ### Get worksheet information from an Open XML package (Visual Basic) Source: https://github.com/officedev/open-xml-docs/blob/main/docs/spreadsheet/how-to-get-worksheet-information-from-a-package.md Instantiate the Sheets class after opening the file for read-only access. This code snippet is part of a larger example for retrieving worksheet information. ```vb Using spreadsheetDocument As SpreadsheetDocument = SpreadsheetDocument.Open(filepath, False) 'Get the presentation part of the presentation document. Dim spreadsheetPart As SpreadsheetPart = spreadsheetDocument.SpreadsheetPart 'Get the list of the sheets in the workbook. Dim sheets As Sheets = spreadsheetPart.WorkbookPart.GetPartsInclusive(Of WorksheetPart)().Select(Function(w) spreadsheetDocument.WorkbookPart.Workbook.Descendants(Of Sheet)().Where(Function(s) spreadsheetDocument.WorkbookPart.GetIdOfPart(w) = s.Id.Value).FirstOrDefault()).Where(Function(s) s IsNot Nothing).ToList() 'Iterate through the sheets and display information. For Each sheet As Sheet In sheets Console.WriteLine("Sheet Name: {0}", sheet.Name) Console.WriteLine("Sheet ID: {0}", sheet.Id) Next End Using ``` -------------------------------- ### Complete Sample Code (C#) Source: https://github.com/officedev/open-xml-docs/blob/main/docs/general/how-to-replace-the-theme-part-in-a-word-processing-document.md The complete C# code example demonstrates how to replace the theme document part in a Word processing document with the theme part from another package. ```csharp using System; using System.IO; using DocumentFormat.OpenXml.Packaging; namespace ReplaceThemePart { class Program { static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine("Usage: ReplaceThemePart "); return; } string filePath = args[0]; string themeFile = args[1]; ReplaceTheme(filePath, themeFile); Console.WriteLine("Theme part replaced successfully."); } public static void ReplaceTheme(string filePath, string themeFile) { using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(filePath, true)) { MainDocumentPart mainPart = wordDoc.MainDocumentPart; // Delete the old theme part ThemePart theme = mainPart.ThemePart; if (theme != null) { mainPart.DeletePart(theme); } // Add a new theme part using (StreamReader streamReader = new StreamReader(themeFile)) { ThemePart newThemePart = mainPart.AddNewPart(); using (StreamWriter streamWriter = new StreamWriter(newThemePart.GetStream())) { streamWriter.Write(streamReader.ReadToEnd()); } } } } } } ``` -------------------------------- ### Create a Minimum Blank Workbook using Open XML SDK Source: https://github.com/officedev/open-xml-docs/blob/main/docs/spreadsheet/structure-of-a-spreadsheetml-document.md This code example demonstrates how to create a basic, empty spreadsheet document using the Open XML SDK. It includes the minimal required elements for a valid workbook. ```csharp using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; public class SpreadsheetHelper { public void CreateBlankSpreadsheet(string filepath) { // Create a spreadsheet document by supplying the file path. using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook)) { // Add a new workbook part to the spreadsheet document. WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart(); // Create a blank Workbook. workbookpart.Workbook = new Workbook(); // Add a new worksheet part to the workbook. WorksheetPart newWorksheetPart = workbookpart.AddNewPart(); // Create a blank "Sheet1". newWorksheetPart.Worksheet = new Worksheet() { CodeName = "Sheet1" }; // Create the Sheets collection. Sheets sheets = workbookpart.Workbook.AppendChild(new Sheets()); // Append a new worksheet and associate it with the rest of the workbook. sheets.AppendChild(new Sheet() { Name = "Sheet1", SheetId = 1, Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(newWorksheetPart) }); // Close the document. workbookpart.Workbook.Save(); spreadsheetDocument.Close(); } } } ``` -------------------------------- ### Get Cell Value (C#) Source: https://github.com/officedev/open-xml-docs/blob/main/docs/spreadsheet/how-to-retrieve-the-values-of-cells-in-a-spreadsheet.md Retrieves the value of a specific cell from an Open XML spreadsheet. This is the main function for getting cell values. ```csharp public static string GetCellValue(Cell theCell) { string value = ""; if (theCell.CellValue != null) { value = theCell.CellValue.InnerText; } return value; } ``` -------------------------------- ### Calling the Sample Method (C#) Source: https://github.com/officedev/open-xml-docs/blob/main/docs/word/how-to-extract-styles-from-a-word-processing-document.md This example demonstrates how to call the ExtractStylesPart method and display the extracted styles to the console. It shows how to retrieve both the styles and stylesWithEffects parts. ```csharp string fileName = "C:\Users\Public\Documents\MyDocument.docx"; XDocument stylesDoc = ExtractStylesPart(fileName, false); if (stylesDoc != null) { Console.WriteLine("Styles Part:"); Console.WriteLine(stylesDoc.ToString()); } else { Console.WriteLine("Could not find the styles part."); } XDocument stylesWithEffectsDoc = ExtractStylesPart(fileName, true); if (stylesWithEffectsDoc != null) { Console.WriteLine("StylesWithEffects Part:"); Console.WriteLine(stylesWithEffectsDoc.ToString()); } else { Console.WriteLine("Could not find the stylesWithEffects part."); } ``` -------------------------------- ### Get Cell Value (Visual Basic) Source: https://github.com/officedev/open-xml-docs/blob/main/docs/spreadsheet/how-to-retrieve-the-values-of-cells-in-a-spreadsheet.md Retrieves the value of a specific cell from an Open XML spreadsheet. This is the main function for getting cell values. ```vb Public Shared Function GetCellValue(theCell As Cell) As String Dim value As String = "" If theCell.CellValue IsNot Nothing Then value = theCell.CellValue.InnerText End If Return value End Function ``` -------------------------------- ### Calling the Sample Method (Visual Basic) Source: https://github.com/officedev/open-xml-docs/blob/main/docs/word/how-to-extract-styles-from-a-word-processing-document.md This example demonstrates how to call the ExtractStylesPart method and display the extracted styles to the console. It shows how to retrieve both the styles and stylesWithEffects parts. ```vb Dim fileName As String = "C:\Users\Public\Documents\MyDocument.docx" Dim stylesDoc As XDocument = ExtractStylesPart(fileName, False) If stylesDoc IsNot Nothing Then Console.WriteLine("Styles Part:") Console.WriteLine(stylesDoc.ToString()) Else Console.WriteLine("Could not find the styles part.") End If Dim stylesWithEffectsDoc As XDocument = ExtractStylesPart(fileName, True) If stylesWithEffectsDoc IsNot Nothing Then Console.WriteLine("StylesWithEffects Part:") Console.WriteLine(stylesWithEffectsDoc.ToString()) Else Console.WriteLine("Could not find the stylesWithEffects part.") End If ``` -------------------------------- ### Example Paragraph Style Definition Source: https://github.com/officedev/open-xml-docs/blob/main/docs/word/how-to-create-and-add-a-paragraph-style-to-a-word-processing-document.md This XML snippet shows an example of a paragraph style definition, including its type, name, based-on, and next style references. ```xml ``` -------------------------------- ### Complete Sample Code (C#) Source: https://github.com/officedev/open-xml-docs/blob/main/docs/spreadsheet/how-to-create-a-spreadsheet-document-by-providing-a-file-name.md This is the complete C# code example for creating a spreadsheet document by providing a file name, including all necessary steps and using statements. ```csharp using System; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; namespace SpreadsheetCreateByName { class Program { static void Main(string[] args) { CreateSpreadsheetDocument("C:\\Users\\Public\\Documents\\MySpreadsheet.xlsx"); } public static void CreateSpreadsheetDocument(string filepath) { // Create a spreadsheet document by supplying the filepath. using (SpreadsheetDocument spreadsheetdocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook)) { // Add a WorkbookPart to the spreadsheet document. WorkbookPart workbookpart; workbookpart = spreadsheetdocument.AddWorkbookPart(); workbookpart.Workbook = new Workbook(); // Add a Sheets container to the Workbook part. Sheets sheets = spreadsheetdocument.WorkbookPart.Workbook.AppendChild(new Sheets()); // Add a new worksheet part to the workbook. WorksheetPart worksheetpart; worksheetpart = spreadsheetdocument.WorkbookPart.AddNewPart(); worksheetpart.Worksheet = new Worksheet(); // Add a new sheet to the Sheets container. var sheet = sheets.AppendChild(new Sheet()); sheet.Name = "Sheet1"; sheet.SheetId = 1; // Add the relationship ID to the sheet. var relationshipId = spreadsheetdocument.WorkbookPart.GetIdOfPart(worksheetpart); sheet.Id = relationshipId; // Close the document. spreadsheetdocument.Close(); } } } } ``` -------------------------------- ### Add and Get IPartRootEventsFeature in Open XML SDK Source: https://github.com/officedev/open-xml-docs/blob/main/docs/general/features.md This snippet illustrates how to add the IPartRootEventsFeature to a part and then retrieve it to get notifications when the part root is modified, loaded, or created. ```csharp OpenXmlPart part = GetSomePart(); part.AddPartRootEventsFeature(); var feature = part.Features.GetRequired(); ``` -------------------------------- ### Add New Sample Script Source: https://github.com/officedev/open-xml-docs/blob/main/samples/README.md Use this PowerShell script to create a scaffold for a new sample and add it to the solution file. Provide the area and name of the sample as arguments. ```powershell ./add-sample.ps1 area name ``` -------------------------------- ### ColorMap Element Example Source: https://github.com/officedev/open-xml-docs/blob/main/docs/presentation/working-with-handout-master-slides.md This XML snippet shows an example of a ColorMap element, which defines color mappings for a slide master. It specifies color names and their corresponding theme colors. ```xml ``` -------------------------------- ### Get slide count and validate indexes (C#) Source: https://github.com/officedev/open-xml-docs/blob/main/docs/presentation/how-to-move-a-slide-to-a-new-position-in-a-presentation.md This method is used to get the number of slides and validate the 'from' and 'to' indexes before moving a slide. It ensures the indexes are within the valid range and are different. ```csharp using DocumentFormat.OpenXml.Presentation; using DocumentFormat.OpenXml.Packaging; using System; using System.Linq; public static void MoveSlide(PresentationDocument presentationDocument, int from, int to) { // Check if the presentation is valid if (presentationDocument?.PresentationPart?.Presentation == null || presentationDocument.PresentationPart.Presentation.SlideIdList == null) { throw new ArgumentNullException(nameof(presentationDocument)); } // Get the number of slides in the presentation int slideCount = presentationDocument.PresentationPart.Presentation.SlideIdList.Count(); // Check if the zero-based indexes are within the range and different from one another if (from < 0 || to < 0 || from >= slideCount || to >= slideCount) { throw new ArgumentOutOfRangeException("from or to index is out of range."); } if (from == to) { return; // No need to move the slide if the indexes are the same } // ... rest of the move slide logic ... SlideIdList slideIdList = presentationDocument.PresentationPart.Presentation.SlideIdList; SlideId slideIdToMove = slideIdList.ChildElements[from] as SlideId; slideIdList.RemoveChild(slideIdToMove); int adjustedTo = (to > from) ? to - 1 : to; slideIdList.InsertAt(slideIdToMove, adjustedTo); presentationDocument.Save(); } ``` -------------------------------- ### Complete Sample Code (Visual Basic) Source: https://github.com/officedev/open-xml-docs/blob/main/docs/general/how-to-replace-the-theme-part-in-a-word-processing-document.md The complete Visual Basic code example demonstrates how to replace the theme document part in a Word processing document with the theme part from another package. ```vb Imports System Imports System.IO Imports DocumentFormat.OpenXml.Packaging Namespace ReplaceThemePart Friend Class Program Shared Sub Main(args As String()) If args.Length <> 2 Then Console.WriteLine("Usage: ReplaceThemePart ") Return End If Dim filePath As String = args(0) Dim themeFile As String = args(1) ReplaceTheme(filePath, themeFile) Console.WriteLine("Theme part replaced successfully.") End Sub Public Shared Sub ReplaceTheme(filePath As String, themeFile As String) Using wordDoc As WordprocessingDocument = WordprocessingDocument.Open(filePath, True) Dim mainPart As MainDocumentPart = wordDoc.MainDocumentPart ' Delete the old theme part Dim theme As ThemePart = mainPart.ThemePart If theme IsNot Nothing Then mainPart.DeletePart(theme) End If ' Add a new theme part Using streamReader As New StreamReader(themeFile) Dim newThemePart As ThemePart = mainPart.AddNewPart(Of ThemePart)() Using streamWriter As New StreamWriter(newThemePart.GetStream()) streamWriter.Write(streamReader.ReadToEnd()) End Using End Using End Using End Sub End Class End Namespace ``` -------------------------------- ### Complete Sample Code (Visual Basic) Source: https://github.com/officedev/open-xml-docs/blob/main/docs/spreadsheet/how-to-create-a-spreadsheet-document-by-providing-a-file-name.md This is the complete Visual Basic code example for creating a spreadsheet document by providing a file name, including all necessary steps and using statements. ```vb Imports System Imports DocumentFormat.OpenXml Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Spreadsheet Namespace SpreadsheetCreateByName Class Program Shared Sub Main(ByVal args() As String) CreateSpreadsheetDocument("C:\\Users\\Public\\Documents\\MySpreadsheet.xlsx") End Sub Public Shared Sub CreateSpreadsheetDocument(ByVal filepath As String) ' Create a spreadsheet document by supplying the filepath. Using spreadsheetdocument As SpreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook) ' Add a WorkbookPart to the spreadsheet document. Dim workbookpart As WorkbookPart workbookpart = spreadsheetdocument.AddWorkbookPart() workbookpart.Workbook = New Workbook() ' Add a Sheets container to the Workbook part. Dim sheets As Sheets = spreadsheetdocument.WorkbookPart.Workbook.AppendChild(Of Sheets)(New Sheets()) ' Add a new worksheet part to the workbook. Dim worksheetpart As WorksheetPart worksheetpart = spreadsheetdocument.WorkbookPart.AddNewPart(Of WorksheetPart)() worksheetpart.Worksheet = New Worksheet() ' Add a new sheet to the Sheets container. Dim sheet As Sheet = sheets.AppendChild(Of Sheet)(New Sheet()) sheet.Name = "Sheet1" sheet.SheetId = 1 ' Add the relationship ID to the sheet. Dim relationshipId As String = spreadsheetdocument.WorkbookPart.GetIdOfPart(worksheetpart) sheet.Id = relationshipId ' Close the document. spreadsheetdocument.Close() End Using End Sub End Class End Namespace ``` -------------------------------- ### Get slide count and validate indexes (Visual Basic) Source: https://github.com/officedev/open-xml-docs/blob/main/docs/presentation/how-to-move-a-slide-to-a-new-position-in-a-presentation.md This method is used to get the number of slides and validate the 'from' and 'to' indexes before moving a slide. It ensures the indexes are within the valid range and are different. ```vb Imports DocumentFormat.OpenXml.Presentation Imports DocumentFormat.OpenXml.Packaging Imports System Imports System.Linq Public Class Program Public Shared Sub MoveSlide(presentationDocument As PresentationDocument, from As Integer, to As Integer) ' Check if the presentation is valid If presentationDocument Is Nothing OrElse presentationDocument.PresentationPart Is Nothing OrElse presentationDocument.PresentationPart.Presentation Is Nothing OrElse presentationDocument.PresentationPart.Presentation.SlideIdList Is Nothing Then Throw New ArgumentNullException(NameOf(presentationDocument)) End If ' Get the number of slides in the presentation Dim slideCount As Integer = presentationDocument.PresentationPart.Presentation.SlideIdList.Count() ' Check if the zero-based indexes are within the range and different from one another If from < 0 OrElse to < 0 OrElse from >= slideCount OrElse to >= slideCount Then Throw New ArgumentOutOfRangeException("from or to index is out of range.") End If If from = to Then Return ' No need to move the slide if the indexes are the same End If ' ... rest of the move slide logic ... Dim slideIdList As SlideIdList = presentationDocument.PresentationPart.Presentation.SlideIdList Dim slideIdToMove As SlideId = slideIdList.ChildElements(from) slideIdList.RemoveChild(slideIdToMove) Dim adjustedTo As Integer = If(to > from, to - 1, to) slideIdList.InsertAt(slideIdToMove, adjustedTo) presentationDocument.Save() End Sub End Class ``` -------------------------------- ### Complete Code Example: Add Custom XML Part Source: https://github.com/officedev/open-xml-docs/blob/main/docs/general/how-to-add-a-new-document-part-to-a-package.md This is the complete code example demonstrating how to add a new custom XML part to a WordprocessingDocument. It includes opening the document, adding the part, writing data, and establishing relationships. ```csharp using System; using System.IO; using System.Xml; using System.Xml.Linq; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; namespace AddCustomXmlPartExample { class Program { static void Main(string[] args) { string filePath = "MyWordDocument.docx"; // Replace with your file path string xmlString = "value"; // Replace with your XML string AddCustomXmlPart(filePath, xmlString); Console.WriteLine("Custom XML part added successfully."); } public static void AddCustomXmlPart(string filePath, string xmlString) { using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(filePath, true)) { MainDocumentPart mainPart = wordDoc.MainDocumentPart; // Define the relationship ID for the custom XML part. string relationshipId = "rId1"; // Add a new custom XML part to the WordprocessingDocument. // You might need to adjust the XmlQualifiedName based on your XML schema. CustomXmlPart customXmlPart = mainPart.AddCustomXmlPart(new System.Xml.XmlDataContractSerializer(typeof(object)).GetXmlSchemaCollection()); // Create a stream to write the custom XML data to the part. using (StreamWriter writer = new StreamWriter(customXmlPart.GetStream())) { writer.Write(xmlString); } // Add a relationship to the custom XML part. // The relationship type and target path might need adjustment. mainPart.AddRelationship(relationshipId, new XName("http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml", "customXml"), "customXml/myCustomXml.xml"); } } } } ``` ```vb Imports System Imports System.IO Imports System.Xml Imports System.Xml.Linq Imports DocumentFormat.OpenXml Imports DocumentFormat.OpenXml.Packaging Namespace AddCustomXmlPartExample Friend Class Program Shared Sub Main(args As String()) Dim filePath As String = "MyWordDocument.docx" ' Replace with your file path Dim xmlString As String = "value" ' Replace with your XML string AddCustomXmlPart(filePath, xmlString) Console.WriteLine("Custom XML part added successfully.") End Sub Public Shared Sub AddCustomXmlPart(filePath As String, xmlString As String) Using wordDoc As WordprocessingDocument = WordprocessingDocument.Open(filePath, True) Dim mainPart As MainDocumentPart = wordDoc.MainDocumentPart ' Define the relationship ID for the custom XML part. Dim relationshipId As String = "rId1" ' Add a new custom XML part to the WordprocessingDocument. ' You might need to adjust the XmlQualifiedName based on your XML schema. Dim customXmlPart As CustomXmlPart = mainPart.AddCustomXmlPart(New System.Xml.XmlDataContractSerializer(GetType(Object)).GetXmlSchemaCollection()) ' Create a stream to write the custom XML data to the part. Using writer As StreamWriter = New StreamWriter(customXmlPart.GetStream()) writer.Write(xmlString) End Using ' Add a relationship to the custom XML part. ' The relationship type and target path might need adjustment. mainPart.AddRelationship(relationshipId, New XName("http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml", "customXml"), "customXml/myCustomXml.xml") End Using End Sub End Class End Namespace ``` -------------------------------- ### Create a simple WordprocessingML document (C#) Source: https://github.com/officedev/open-xml-docs/blob/main/docs/word/structure-of-a-wordprocessingml-document.md Uses the Open XML SDK to create a simple WordprocessingML document with specified text. Ensure the necessary namespaces are imported. ```csharp using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System; namespace StructureOfAWordprocessingMLDocument { class Program { static void Main(string[] args) { // The following code creates a WordprocessingML document that contains the text passed in as the second parameter. // Create a WordprocessingML document object. using (WordprocessingDocument wordDocument = WordprocessingDocument.Create("HelloWorld.docx", WordprocessingDocumentType.Document)) { // Add a main document part. MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); // Create the document structure and add content to it. mainPart.Document = new Document(); // Create a new paragraph. Paragraph para = new Paragraph(); para.AppendChild(new Run(new Text("Hello World!"))); // Create a new section. SectionProperties sectionProperties = new SectionProperties(); sectionProperties.AppendChild(new ParagraphMarkRunProperties()); // Add the section properties to the document. mainPart.Document.AppendChild(sectionProperties); // Create the body and add the paragraph to it. mainPart.Document.AppendChild(new Body(para)); // Close the document object. mainPart.Document.Save(); } } } } ``` -------------------------------- ### Get Worksheet Part by ID (C#) Source: https://github.com/officedev/open-xml-docs/blob/main/docs/spreadsheet/how-to-retrieve-the-values-of-cells-in-a-spreadsheet.md Retrieves the WorksheetPart using its relationship ID. ```csharp WorksheetPart worksheetPart = (WorksheetPart)spreadsheetDocument.WorkbookPart.GetPartById(relationshipId); ``` -------------------------------- ### Complete AddCustomUI Method Example Source: https://github.com/officedev/open-xml-docs/blob/main/docs/spreadsheet/how-to-add-custom-ui-to-a-spreadsheet-document.md Provides the complete C# and Visual Basic code for the AddCustomUI method, which integrates custom ribbon UI into an Excel spreadsheet. ```csharp using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Office.CustomUI; using System.IO; public static class SpreadsheetHelper { public static void AddCustomUI(string filename, string customUIContent) { // Open the spreadsheet document in read/write mode. using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filename, true)) { // Get the workbook part. WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart; if (workbookPart == null) { // Handle error: Workbook part not found. return; } // Get the ribbon part, or create it if it doesn't exist. RibbonExtensibilityPart ribbonPart = workbookPart.RibbonExtensibilityPart; if (ribbonPart == null) { ribbonPart = workbookPart.AddNewPart(); } // Add the custom UI to the ribbon part. ribbonPart.CustomUI = new CustomUI(customUIContent); // Save the changes to the document. spreadsheetDocument.Save(); } } // Example usage: // private const string customUIXml = " // //