Server-side word automation

送分小仙女□ 提交于 2019-12-13 12:23:59

问题


I am looking for alternatives to using openxml for a server-side word automation project. Does anyone know any other ways that have features to let me manipulate word bookmarks and tables?


回答1:


I am currently doing a project of developing a word automation project for my company and I am using DocX Very simple and straight forward API to work with. The approach I am using is, whenever I need to work with XML directly, this API has a property named "xml" in the Paragraph class which gives you access to the underlying xml direclty so that I can work with it. The best part is its not breaking the xml and not corrupting the resulting document. Hope this helps!

Example code using 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..");
                  }
             }
         }
    }

Alternative API exclusively to work with bookmarks is .. http://simpleooxml.codeplex.com/

Example on how to delete text from bookmarkstart to bookmarkend using this 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);

Loading the word document into different API's from memory stream.

//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); 


来源:https://stackoverflow.com/questions/9810718/server-side-word-automation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!