简体   繁体   中英

Unable to fill Content Control in Word using OpenXML

i am new to OpenXML and i am about to pull my hair on this issue. Help would really appreciated.

Overview is that i am trying to fill the word document content template thru asp.net.

I was easily able to populate the fields using CustomXML, BUT THE document i am trying to fill is also mapped with SharePoint document library. So when i upload the document in SharePoint library it will auto populate the columns from the content controls on Word document. Now using custom XML is ruining that setting. And using OpenXML to fill data is not working when the controls are mapped to SharePoint.

Please help with sample code or the right direction.

This is exactly what we did in our project:) lucky you.

first you need to create event receiver for that document library. and you need to implement ItemUpdated and ItemAdded. see http://www.dotnetcurry.com/ShowArticle.aspx?ID=649 http://blogs.msdn.com/b/brianwilson/archive/2007/03/05/part-1-event-handlers-everything-you-need-to-know-about-microsoft-office-sharepoint-portal-server-moss-event-handlers.aspx

//code for event receiver.. This will give you name of content control and its values

 Dictionary<string, string> results = new Dictionary<string, string>();
            using (Stream stream = file.OpenBinaryStream(SPOpenBinaryOptions.SkipVirusScan)) {

                using (WordprocessingDocument doc = WordprocessingDocument.Open(stream, true)) {
                    var contentControls = doc.MainDocumentPart
                        .GetXDocument()
                        .Descendants(w + "sdt");

                    foreach ( var contentControl in contentControls ) 
                    {
                        string key = (string)contentControl.Descendants(w + "sdtPr").Elements(w + "alias").Attributes(w + "val").FirstOrDefault();
                        string val = GetTextFromContentControl(contentControl);
                        results[key] = val;
                    }

 }

static string GetTextFromContentControl(XElement contentControlNode) {
            return contentControlNode.Descendants(w + "p")
                .Select
                (
                    p => p.Elements()
                          .Where(z => z.Name == r || z.Name == ins || z.Name == br)
                          .Descendants()
                          .Where(z => z.Name == w + "t" || z.Name == w + "br")
                          .StringConcatenate(element => (string)element + (element.Name == w + "br" ? Environment.NewLine : "")) + Environment.NewLine
                ).StringConcatenate();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM