Question

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?

Was it helpful?

Solution

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); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top