0
votes

Using Visual Studio 2010 and Microsoft Word 2010:

I have a document that Restrict Editing is enabled to Allow only "filling in forms" when editing in the document.

On the Word document I have Text Form Fields I added from the Developer tab from the Legacy Controls.

What I want to do is populate some of these Form Fields with data (like their name, address, etc...stuff I already know and already pulled from the database).

What I've tried:

using System;
using System.Configuration;
using System.IO;
using Microsoft.Office.Interop.Word;

var oWordApplication = new ApplicationClass();

object missing = System.Reflection.Missing.Value;
object fileName = ConfigurationManager.AppSettings["DocxPath"];
object newTemplate = false;
object docType = 0;
object isVisible = true;

var oWordDoc = oWordApplication.Documents.Add(fileName, newTemplate, docType, isVisible);

                if (oWordDoc.Bookmarks.Exists("txtName"))
                {
                    oWordDoc.Bookmarks["txtName"].Range.Text = "Test Field Entry from webform";
                }

I'm able to find the field I want to edit but I get the following error when I try to modify the text:

You are not allowed to edit this selection because it is protected.
1
Side note: using interop with Office applications on server (non-interactive sessions) is not supported... - Alexei Levenkov
Well....crap :) So it won't work or is it more trouble than it's worth? - killerbunnyattack
You can use OpenXML for working with newer word documents(.docx) on server side. It is little more complicated than interop though. - m0s

1 Answers

0
votes

Here is what I do. Make a class that can be mapped directly to your word template then serialize the class to xml and use my methods below.

    public static void ReplaceCustomXML(string fileName, string customXML)
    {
        using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(fileName, true))
        {
            MainDocumentPart mainPart = wordDoc.MainDocumentPart;
            mainPart.DeleteParts<CustomXmlPart>(mainPart.CustomXmlParts);
            //Add a new customXML part and then add the content. 
            CustomXmlPart customXmlPart = mainPart.AddCustomXmlPart(CustomXmlPartType.CustomXml);
            //Copy the XML into the new part. 
            using (StreamWriter ts = new StreamWriter(customXmlPart.GetStream())) ts.Write(customXML);
        }
    }

    public static string SerializeObjectToString(this object obj)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            XmlSerializer x = new XmlSerializer(obj.GetType());
            x.Serialize(stream, obj);
            return Encoding.Default.GetString(stream.ToArray());
        }
    }

I would recommend reviewing this article as it makes updating docs a snap with openxml.

http://seroter.wordpress.com/2009/12/23/populating-word-2007-templates-through-open-xml/