none
copy a vbaProject part from one SreadsheetDocument to another? RRS feed

  • Question

  • I'm a total newbie with OpenXML, but I have been able to figure out how to do 3/4 of what I need to do. Stumped on the last part though.

    What I need is to be able to start with a .xlsm macro enabled document, read it as a stream, remove the vbaProject part, and save it to a new stream as a macro free .xlsx type document and then go off and work with it....   Then, later, I would like to re-attach the previously removed vbaProject part, and resave the modifed document as a macro enabled xslm document once more.

    I can do the first two parts - reading and removing of the vbaProject part - just fine.

    I'm stumped on how to add the vbaProject part back in.

    I tried to do something like this

      xlsm.ChangeDocumentType(SpreadDocumentType.MacroEnabledWorkbook);
      xslm.AddPart(vbaPart)

    where xlsm is an instance of SpreadsheetDocument, read from a stream, and vbaPart is the object returned from the original document's WorkBookPart.Parts collection.

    The call works, but if I then ask for  xlsm.WorkbookPart.Parts  I do not see my newly added part.

    Saving the new file increments the file size by about the expected amount, and I can read the file in Excel.  But no macros are present.


    Any ideas would be very much appreciated.  I'm stuck.

    Thanks.

    roger reynolds
    Wednesday, June 17, 2009 10:27 PM

Answers

  • OK, I figured this out and here's the answer, just for reference:

    var ms = ... some stream containing an xlsm document
    var xlsx = SpreadsheetDocument.Open(ms, true);
    xlsx.ChangeDocumentType(SpreadsheetDocumentType.MacroEnabledWorkbook);
    
    var vbaProject = "http://schemas.microsoft.com/office/2006/relationships/vbaProject";
    var contentType = "application/vnd.ms-office.vbaProject";
    var newPart = xlsx.WorkbookPart.AddExtendedPart(vbaProject, contentType, "bin", "someNewId");
    newPart.FeedData(streamDataOfPreviouslySavedVbaPart);
    xlsx.Close();
    

    roger reynolds
    Thursday, June 18, 2009 3:42 PM