0

私は問題があります、

顧客から提供された .dotx ファイルがあります。Word の開発者モードで追加されたさまざまな種類のフィールドが多数含まれています。

この dotx を使用して、値を入力できるようにしたいと考えています。

C#コードでこれを行うにはどうすればよいですか?

4

1 に答える 1

3

Microsoft OpemXML SDK を使用すると、c# を使用して docx/dotx ファイルを操作できます。Microsoft OpenXML SDK は、ここからダウンロードできます。

最初に dotx ファイルのコピーを作成する必要があります。次に、テンプレートでフィールド/コンテンツ プレースホルダーを見つけます。

以下に小さな例を示します (リッチ テキスト ボックスのコンテンツ フィールドを持つ単純な Word テンプレートを使用):

// First, create a copy of your template.
File.Copy(@"c:\temp\mytemplate.dotx", @"c:\temp\test.docx", true);

using (WordprocessingDocument newdoc = WordprocessingDocument.Open(@"c:\temp\test.docx", true))
{
  // Change document type (dotx->docx)
  newdoc.ChangeDocumentType(WordprocessingDocumentType.Document);

  // Find all structured document tags
  IEnumerable<SdtContentRun> placeHolders = newdoc.MainDocumentPart.RootElement.Descendants<SdtContentRun>();

  foreach (var cp in placeHolders)
  {
    var r = cp.Descendants<Run>().FirstOrDefault();

    r.RemoveAllChildren(); // Remove children
    r.AppendChild<Text>(new Text("my text")); // add new content
  }        
}

上記の例は非常に単純な例です。Word テンプレートの構造に合わせて調整する必要があります。

お役に立てれば。

于 2011-11-29T20:16:17.220 に答える