-
Office Interop: Attach a custom template and update styles in Word 2007 using C#
No CommentsHi, in this opportunity you will see how to attach a given template into a Word 2007 document programatically (C#), and subsequently update the styles that were modified.
Sample Solution
If you like to see the code working, I’m attaching in this post a really simple sample solution that you can download and use it at will. The sample consists on a VSTO Word 2007 add-in solution that when debugs it opens a Word 2007 instance. This Word 2007 instance has plugged-in an additional ribbon bar with one button named AttachTemplate that will attach a provided template every time it is clicked.
The Code
The code is really small and seamless; seems that the guys of Interop did a great job with this
. First of all, we need to gather the active Word Document which is the object representation of our Word document instance (For more information, see Document Interface).The Document interface exposes two methods that comes in handy for our mission: set_AttachedTemplate and UpdateStyles. When we call the set_AttachedTemplate, Interop resets the Document.AttachedTemplate property and performs additional tasks such as manipulating the Styles section of the OpenXml (more precisely the word\styles.xml XmlPart).
(For more information, see AttachedTemplate property)
At this moment, all elements that compose a template have been re assigned to match the new ones, but you won’t see any style changes. The document content and the styles pane will stay unaltered. Here is when UpdateStyles method comes into action by adding the new styles into the style pane and forcing all the document content styles to get updated instantly.
See it by yourself:
private void AttachTemplate(Word.Document document, string templateFilePath) { object oTemplate = (object)templateFilePath; document.set_AttachedTemplate(ref oTemplate); document.UpdateStyles(); }
Hope it helped!
See you! -
Leave a comment
Your email address will not be published.