Open XML SDK - Adding a macro programatically to a Word 2007 document

核能气质少年 提交于 2019-12-21 05:24:10

问题


I am trying to dynamically add a new custom ribbon in a Word 2007 document following teh manual method described in this article :- http://msdn.microsoft.com/en-us/library/aa338202(v=office.12).aspx.

The article specifies the following :-

a) Create a XML file named customUI.xml which will contain the elements you want to display in the tab and put the same in a folder named customUI.

b) Rename your Word 2007 document to .zip. Add the above "customUI" folder to the zip file.

c) Add the following relationship to the "_rels/rels" file in the .zip file :-

<Relationship Type="http://schemas.microsoft.com/office/2006/
  relationships/ui/extensibility" Target="/customUI/customUI.xml" 
  Id="customUIRelID" />

Do we have some code sample to achieve the same using OpenXML SDK? For example, how to add the "RibbonExtensibilityPart" (which contains the ribbon XML) to the document?

EDIT :-

This is how I did the above mentioned steps:-

 string documentFileName = <path of the docx file>;
  string ribbonXml        =  <path of the ribbon XML file>;
 using (WordprocessingDocument myDoc = WordprocessingDocument.Open(documentFileName, true))
 {
   MainDocumentPart mainPart = myDoc.MainDocumentPart;

   if (myDoc.GetPartsCountOfType<RibbonExtensibilityPart>() > 0)
      myDoc.DeletePart(myDoc.GetPartsOfType<RibbonExtensibilityPart>().First());

   RibbonExtensibilityPart ribbonExtensibilityPart = myDoc.AddNewPart<RibbonExtensibilityPart>();
   ribbonExtensibilityPart.CustomUI = new DocumentFormat.OpenXml.Office.CustomUI.CustomUI(File.ReadAllText(ribbonXML));

   myDoc.CreateRelationshipToPart(ribbonExtensibilityPart);
 }

and I am able to see the new ribbon with the elements in it. However, I have buttons in the ribbon and I want to add handle actions on those buttons. Following is what my Ribbon XML looks like :-

<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui">
  <ribbon>
    <tabs>
      <tab id="CustomTab" label="My Tab">
        <group id="MyGroup" label="My Group" >
          <button id="Button1" label="My Large Button" 
            size="large"/>
          <button id="Button2" label="My Normal Button" 
            size="normal" *onAction="ThisDocument.MyOtherButtonMacro"* />
        </group >
      </tab>
    </tabs>
  </ribbon>
</customUI>

have a look at the "onAction="ThisDocument.MyOtherButtonMacro". I know I can write Macro function in the document. However, as the custom ribbon will be added dynamically on the server-side, I am not sure how I can add the macro dynamically. Could anyone help?

来源:https://stackoverflow.com/questions/4499425/open-xml-sdk-adding-a-macro-programatically-to-a-word-2007-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!