how can I put a content in a mergefield in docx

后端 未结 3 699
被撕碎了的回忆
被撕碎了的回忆 2021-01-13 15:18

I\'m developing a web application with asp.net and I have a file called Template.docx that works like a template to generate other reports. Inside this Template.docx I have

相关标签:
3条回答
  • 2021-01-13 15:57

    You could try http://www.codeproject.com/KB/office/Fill_Mergefields.aspx which uses the Open XML SDK to do this.

    0 讨论(0)
  • 2021-01-13 16:09

    I know this is an old post, but I could not get the accepted answer to work for me. The project linked would not even compile (which someone has already commented in that link). Also, it seems to use other Nuget packages like WPFToolkit.

    So I'm adding my answer here in case someone finds it useful. This only uses the OpenXML SDK 2.5 and also the WindowsBase v4. This works on MS Word 2010 and later.

    string sourceFile = @"C:\Template.docx";
    string targetFile = @"C:\Result.docx";
    File.Copy(sourceFile, targetFile, true);
    using (WordprocessingDocument document = WordprocessingDocument.Open(targetFile, true))
    {
        // If your sourceFile is a different type (e.g., .DOTX), you will need to change the target type like so:
        document.ChangeDocumentType(WordprocessingDocumentType.Document);
    
        // Get the MainPart of the document
        MainDocumentPart mainPart = document.MainDocumentPart;
        var mergeFields = mainPart.RootElement.Descendants<FieldCode>();
    
        var mergeFieldName = "SenderFullName";
        var replacementText = "John Smith";
    
        ReplaceMergeFieldWithText(mergeFields, mergeFieldName, replacementText);                   
    
        // Save the document
        mainPart.Document.Save();
    
    }
    
    
    private void ReplaceMergeFieldWithText(IEnumerable<FieldCode> fields, string mergeFieldName, string replacementText)
    {
        var field = fields
            .Where(f => f.InnerText.Contains(mergeFieldName))
            .FirstOrDefault();
    
        if (field != null)
        {
            // Get the Run that contains our FieldCode
            // Then get the parent container of this Run
            Run rFldCode = (Run)field.Parent; 
    
            // Get the three (3) other Runs that make up our merge field
            Run rBegin = rFldCode.PreviousSibling<Run>();
            Run rSep = rFldCode.NextSibling<Run>();
            Run rText = rSep.NextSibling<Run>();
            Run rEnd = rText.NextSibling<Run>();
    
            // Get the Run that holds the Text element for our merge field
            // Get the Text element and replace the text content 
            Text t = rText.GetFirstChild<Text>();
            t.Text = replacementText;
    
            // Remove all the four (4) Runs for our merge field
            rFldCode.Remove();
            rBegin.Remove();
            rSep.Remove();
            rEnd.Remove();
        }
    
    }
    

    What the code above does is basically this:

    • Identify the 4 Runs that make up the merge field named "SenderFullName".
    • Identify the Run that contains the Text element for our merge field.
    • Remove the 4 Runs.
    • Update the text property of the Text element for our merge field.

    UPDATE

    For anyone interested, here is a simple static class I used to help me with replacing merge fields.

    0 讨论(0)
  • 2021-01-13 16:12

    Frank Fajardo's answer was 99% of the way there for me, but it is important to note that MERGEFIELDS can be SimpleFields or FieldCodes.

    In the case of SimpleFields, the text runs displayed to the user in the document are children of the SimpleField.

    In the case of FieldCodes, the text runs shown to the user are between the runs containing FieldChars with the Separate and the End FieldCharValues. Occasionally, several text containing runs exist between the Separate and End Elements.

    The code below deals with these problems. Further details of how to get all the MERGEFIELDS from the document, including the header and footer is available in a GitHub repository at https://github.com/mcshaz/SimPlanner/blob/master/SP.DTOs/Utilities/OpenXmlExtensions.cs

    private static Run CreateSimpleTextRun(string text)
    {
        Run returnVar = new Run();
        RunProperties runProp = new RunProperties();
        runProp.Append(new NoProof());
        returnVar.Append(runProp);
        returnVar.Append(new Text() { Text = text });
        return returnVar;
    }
    
    private static void InsertMergeFieldText(OpenXmlElement field, string replacementText)
    {
        var sf = field as SimpleField;
        if (sf != null)
        {
            var textChildren = sf.Descendants<Text>();
            textChildren.First().Text = replacementText;
            foreach (var others in textChildren.Skip(1))
            {
                others.Remove();
            }
        }
        else
        {
            var runs = GetAssociatedRuns((FieldCode)field);
            var rEnd = runs[runs.Count - 1];
            foreach (var r in runs
                .SkipWhile(r => !r.ContainsCharType(FieldCharValues.Separate))
                .Skip(1)
                .TakeWhile(r=>r!= rEnd))
            {
                r.Remove();
            }
            rEnd.InsertBeforeSelf(CreateSimpleTextRun(replacementText));
        }
    }
    
    private static IList<Run> GetAssociatedRuns(FieldCode fieldCode)
    {
        Run rFieldCode = (Run)fieldCode.Parent;
        Run rBegin = rFieldCode.PreviousSibling<Run>();
        Run rCurrent = rFieldCode.NextSibling<Run>();
    
        var runs = new List<Run>(new[] { rBegin, rCurrent });
    
        while (!rCurrent.ContainsCharType(FieldCharValues.End))
        {
            rCurrent = rCurrent.NextSibling<Run>();
            runs.Add(rCurrent);
        };
    
        return runs;
    }
    
    private static bool ContainsCharType(this Run run, FieldCharValues fieldCharType)
    {
        var fc = run.GetFirstChild<FieldChar>();
        return fc == null
            ? false
            : fc.FieldCharType.Value == fieldCharType;
    }
    
    0 讨论(0)
提交回复
热议问题