【问题标题】:Manipulating dotx templates with C# [closed]使用 C# 操作 dotx 模板 [关闭]
【发布时间】:2011-11-29 11:25:22
【问题描述】:

我有问题,

我有一个客户提供的 .dotx 文件。它包含在 Word 的开发者模式中添加的许多不同类型的字段。

我希望能够使用这个 dotx 并用值填充它。

如何在 C# 代码中执行此操作?

【问题讨论】:

  • 对于您可以使用的内容是否有任何限制。例如,在将运行您的程序的服务器/客户端上安装 Office?
  • 好吧,我可以在服务器/客户端上安装office等。但重要的是数据来自数据库或网络表单。因此,我需要能够从代码中操作 dotx 以生成完成的文档。
  • @Bali C,我有,感谢您指出。

标签: c# openxml-sdk word-template


【解决方案1】:

Microsoft OpemXML SDK 允许您使用 c# 操作 docx/dotx 文件。您可以从here 下载 Microsoft OpenXML SDK。

您应该首先创建 dotx 文件的副本。然后在模板中找到字段/内容占位符。

这是一个小例子(使用带有富文本框内容字段的简单单词模板):

// 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
  }        
}

上面的例子是一个非常简单的例子。您必须使其适应您的单词模板结构。

希望,这会有所帮助。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-03-14
  • 2014-05-07
  • 1970-01-01
  • 1970-01-01
  • 2017-06-24
  • 1970-01-01
  • 1970-01-01
  • 2010-09-14
相关资源
最近更新 更多