【问题标题】:Server-side word automation服务器端词自动化
【发布时间】:2012-03-23 05:43:15
【问题描述】:

我正在寻找将 openxml 用于服务器端单词自动化项目的替代方法。有谁知道任何其他具有让我操作单词书签和表格的功能的方法?

【问题讨论】:

  • 您要自动化什么以及为什么 openxml 不能满足您的需求,如果没有这些详细信息,将很难提供其他选项。
  • 我正在尝试删除书签开始和书签结束中的所有文本。据我所知,openxml 不允许我这样做
  • 现在知道你想做什么看看这个问题,它基本上和你想做的事情是一样的。 stackoverflow.com/questions/3308299/…
  • @JohnBaum 你应该在问题本身中提到这一点..
  • 那个方法对我不起作用。我的书签之后的下一个兄弟不是文档中实际书签的唯一元素部分。

标签: c# word-automation


【解决方案1】:

我目前正在为我的公司开发一个单词自动化项目,我正在使用 DocX 非常简单直接的 API 来使用。我使用的方法是,每当我需要直接使用 XML 时,此 API 在 Paragraph 类中有一个名为“xml”的属性,它使您可以直接访问底层 xml,以便我可以使用它。最好的部分是它不会破坏 xml 并且不会破坏生成的文档。希望这会有所帮助!

使用 DocX 的示例代码..

 XNamespace ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
    using(DocX doc = DocX.Load(@"c:\temp\yourdoc.docx"))
    {
         foreach( Paragraph para in doc.Paragraphs )
         {
             if(para.Xml.ToString().Contains("w:Bookmark"))
             {
                 if(para.Xml.Element(ns + "BookmarkStart").Attribute("Name").Value == "yourbookmarkname")
                  {
                          // you got to your bookmark, if you want to change the text..then 
                          para.Xml.Elements(ns + "t").FirstOrDefault().SetValue("Text to replace..");
                  }
             }
         }
    }

专门用于书签的替代 API 是 ..http://simpleooxml.codeplex.com/

有关如何使用此 API 从书签开始到书签结束删除文本的示例..

 MemoryStream stream = DocumentReader.Copy(string.Format("{0}\\template.docx", TestContext.TestDeploymentDir));
 WordprocessingDocument doc = WordprocessingDocument.Open(stream, true);
 MainDocumentPart mainPart = doc.MainDocumentPart;

 DocumentWriter writer = new DocumentWriter(mainPart);

 //Simply Clears all text between bookmarkstart and end
 writer.PasteText("", "YourBookMarkName");


 //Save to the memory stream, and then to a file
 writer.Save();

 DocumentWriter.StreamToFile(string.Format("{0}\\templatetest.docx", GetOutputFolder()), stream);

将word文档从内存流中加载到不同的API中。

//Loading a document file into memorystream using SimpleOOXML API
MemoryStream stream = DocumentReader.Copy(@"c\template.docx");

//Opening it from the memory stream as OpenXML document
WordprocessingDocument doc = WordprocessingDocument.Open(stream, true);

//Opening it as DocX document for working with DocX Api
DocX document = DocX.Load(stream); 

【讨论】:

  • 我可以使用 docX 访问 word doc 中的书签吗?
  • 不是开箱即用的..但您可以直接从底层 xml 中获取它..取决于您的要求..
  • 你能举例说明我如何使用 xml 来获取书签
  • 这个api是否支持查找书签并在其后直接写一些文字?这是我需要完成的另一件事
  • 这就是 PasteText 方法的作用.. writer.PasteText("write some text", "yourBookMarkName"); ..就这么简单..
猜你喜欢
  • 2015-05-28
  • 1970-01-01
  • 2011-02-23
  • 2021-09-07
  • 1970-01-01
  • 1970-01-01
  • 2018-06-14
  • 2010-11-01
  • 2016-09-01
相关资源
最近更新 更多