是否可以将Mergefields添加到现有 .docx 文档不使用Interop,仅使用CodeBehind的开放SDK处理?

没有正确的解决方案

其他提示

是的,这是可能的,我在下面创建了一个小方法,您只需将要分配给合并字段的名称即可为您创建。下面的代码用于创建一个新文档,但使用该方法将方法添加到现有文档应该很容易,希望这对您有帮助:

using System;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            using (WordprocessingDocument package = WordprocessingDocument.Create("D:\\ManualMergeFields.docx", WordprocessingDocumentType.Document))
            {
                package.AddMainDocumentPart();

                Paragraph nameMergeField = CreateMergeField("Name");
                Paragraph surnameMergeField = CreateMergeField("Surname");

                Body body = new Body();
                body.Append(nameMergeField);
                body.Append(surnameMergeField);
                package.MainDocumentPart.Document = new Document(new Body(body));
            }
        }

        static Paragraph CreateMergeField(string name)
        {
            if (!String.IsNullOrEmpty(name))
            {
                string instructionText = String.Format(" MERGEFIELD  {0}  \\* MERGEFORMAT", name);
                SimpleField simpleField1 = new SimpleField() { Instruction = instructionText };

                Run run1 = new Run();

                RunProperties runProperties1 = new RunProperties();
                NoProof noProof1 = new NoProof();

                runProperties1.Append(noProof1);
                Text text1 = new Text();
                text1.Text = String.Format("«{0}»", name);

                run1.Append(runProperties1);
                run1.Append(text1);

                simpleField1.Append(run1);

                Paragraph paragraph = new Paragraph();
                paragraph.Append(new OpenXmlElement[] { simpleField1 });
                return paragraph;
            }
            else return null;
        }
    }
}

您可以从此URL下载开放的XML生产力工具(如果还没有)http://www.microsoft.com/download/en/details.aspx?id=5124此工具具有“反射代码”功能。创建上面的样本。运气好

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top