static void Main(string[] args) { using (WordprocessingDocument destDoc = WordprocessingDocument.Create("destination.docm", WordprocessingDocumentType.MacroEnabledDocument)) { WordprocessingDocument srcDoc = WordprocessingDocument.Open("macrosource.docm", false); MainDocumentPart mainPart = destDoc.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("This is a copied macro enabled doc. Hit Ctrl+Insert Now.")); // Get VBA parts from source document VbaProjectPart vbaSrc = srcDoc.MainDocumentPart.VbaProjectPart; VbaDataPart vbaDatSrc = vbaSrc.VbaDataPart; CustomizationPart keymapSrc = srcDoc.MainDocumentPart.CustomizationPart; // Create VBA parts in destination document VbaProjectPart vbaProjectPart1 = mainPart.AddNewPart <VbaProjectPart>("rId9"); VbaDataPart vbaDataPart1 = vbaProjectPart1.AddNewPart <VbaDataPart>("rId1"); CustomizationPart customKeyMapPart = mainPart.AddNewPart <CustomizationPart>("rId10"); // Copy part contents vbaProjectPart1.FeedData(vbaSrc.GetStream()); vbaDataPart1.FeedData(vbaDatSrc.GetStream()); customKeyMapPart.FeedData(keymapSrc.GetStream()); } }
/// <summary> /// This function doesn't have anything to do specifically with this library, but is something that can be done /// simply with OpenXML /// </summary> private static void ReplaceVbaParts() { Console.WriteLine("Replace an existing vbProject of an Excel file with another vbProject"); Console.WriteLine(); Console.WriteLine("Enter path of workbook to open: "); string path = Console.ReadLine(); if (!File.Exists(path)) { throw new FileNotFoundException(String.Format("File {0} does not exist", path)); } Console.WriteLine("Enter path of .bin file to open"); string binPath = Console.ReadLine(); if (!File.Exists(binPath)) { throw new FileNotFoundException(String.Format("File {0} does not exist", binPath)); } using (SpreadsheetDocument wb = SpreadsheetDocument.Open(path, true)) { var wbPart = wb.WorkbookPart; using (var storage = new VbProject(wbPart)) { PrintStorage(storage); } Console.WriteLine(); Console.WriteLine("---------------REPLACING VBA PART----------------"); Console.WriteLine(); // Replace parts var vba = wbPart .GetPartsOfType <VbaProjectPart>() .SingleOrDefault(); if (vba != null) { wbPart.DeletePart(vba); } VbaProjectPart newVbaPart = wbPart.AddNewPart <VbaProjectPart>(); using (var stream = File.OpenRead(binPath)) { newVbaPart.FeedData(stream); } using (var storage = new VbProject(wbPart)) { PrintStorage(storage); } wbPart.Workbook.Save(); } }