質問

既存のマージフィールドを追加することは可能ですか? .docx Interopを使用せずにドキュメントCodeBehindからOpen 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だから、MS Wordドキュメントでマージフィールドを手動で作成し、生産性ツールでドキュメントを開き、これをコードで行う方法に関するC#コードサンプルを表示できます!上記のサンプルを作成します

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top