
How practically would it be if a word document could be filled with some values at predefined places (like placeholder)? In one of my customer projects the requirements were like this:
The customer manages his service agreements in a SharePoint list. Endusers type in the data in a normal SharePoint form. After that they can generate a word document with exactly these data. The data will be transformed into a word template for those agreements. So it is obvious that the data from the sharepoint listitem should be displayed and saved in the word template at certain predefined places. And this scenario can be true by using openxml.
Let me explain with an example more simple. We just insert values from c# into the word document. I’ll show you what you need to do in word and what you need to do in code.
Step 1: Prepare the word document
Insert a custom property
In word open the start menu – extended properties and in the tab customize: There you can add you own “variables” or better properties.
There we insert these properties:
1. Location
2. Status
Set custom property into word body
To insert those properties into text, we do the following: In word just open the tab “Insert” and look for the quick edit blocks and then fields. In the category docproperty you’ll find your custom properties.
Repeat it for location. That’s it on this side. Now let’s see what we need to do in code.
Step 2: Using OpenXml to fill custom properties with values
First we have to get the file and open it by using the wordprocessor. Then we go into the custom properties and change the values and save those.
[sourcecode language=”csharp”]
using (WordprocessingDocument doc = WordprocessingDocument.Open(tempFilePath, true))
{
//Reading Properties Part
var customProps = doc.CustomFilePropertiesPart;
var props = customProps.Properties;
CustomDocumentProperty prop = null;
var searchProp = props.Where(p => ((CustomDocumentProperty)p).Name.Value == “Location”).FirstOrDefault();
if (searchProp != null)
{
prop = searchProp as CustomDocumentProperty;
prop.VTLPWSTR = new DocumentFormat.OpenXml.VariantTypes.VTLPWSTR(“Germany”);
}
var searchProp2 = props.Where(p => ((CustomDocumentProperty)p).Name.Value == “Status”).FirstOrDefault();
if (searchProp2 != null)
{
prop = searchProp2 as CustomDocumentProperty;
prop.VTLPWSTR = new DocumentFormat.OpenXml.VariantTypes.VTLPWSTR(“Assigned”);
}
//Save the changes
DocumentSettingsPart settingsPart = doc.MainDocumentPart.GetPartsOfType
UpdateFieldsOnOpen updateFields = new UpdateFieldsOnOpen();
updateFields.Val = new DocumentFormat.OpenXml.OnOffValue(true);
settingsPart.Settings.PrependChild
settingsPart.Settings.Save();
doc.MainDocumentPart.Document.Save();
}
[/sourcecode]
After running the code you’ll see your values in the word document if you open it. It maybe that word asks if you want to refresh data. Just click OK.
Hope this helps you.
Leave a Reply
You must be logged in to post a comment.