using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; // Open the document for editing using (WordprocessingDocument doc = WordprocessingDocument.Open("myDocument.docx", true)) { // Get the main document part MainDocumentPart mainPart = doc.MainDocumentPart; // Create a new style part StyleDefinitionsPart stylePart = mainPart.AddNewPart("rId4"); // Create new styles for the part Styles styles = new Styles(); // Add styles and other formatting elements to the new style definitions part. stylePart.Styles = styles; // Save changes to the document doc.Save(); }
using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; // Open the workbook for editing using (SpreadsheetDocument doc = SpreadsheetDocument.Open("myWorkbook.xlsx", true)) { // Get the workbook part WorkbookPart workbookPart = doc.WorkbookPart; // Create a new worksheet part WorksheetPart worksheetPart = workbookPart.AddNewPartIn this second example code, the MainDocumentPart.AddNewPart method is used to add a new worksheet part to an Excel document. The code retrieves the workbook part of the Excel document, creates a new WorksheetPart object using the AddNewPart method, and adds it to the workbook. Finally, worksheet elements are added to the new worksheet part, and the workbook is saved. Package library: DocumentFormat.OpenXml.Packaging("rId4"); // Create new worksheet elements for the part Worksheet worksheet = new Worksheet(); // Add sheet data and formatting elements to the new worksheet part. worksheetPart.Worksheet = worksheet; // Save changes to the workbook doc.Save(); }