Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Open XML to read already opened Word documents?

All examples and implementations I've seen employ some type of code like:

//filePath is some path to a docx file
using (WordprocessingDocument wpd = WordprocessingDocument.Open(filePath, true))
{
    //Do stuff here
}

which requires your file be closed. I want to be able to use the Open XML SDK operations on an already open document because I'll want to do stuff while the user is actively looking through the document, and I won't necessarily want to save it.

Is this possible? I realize Word probably locks the document if it is open, so you are unable to open the file (even for Read-Only). Is there any way around it?

It'd be really nice if I could somehow use the Open XML SDK on already open documents. One idea I've had is saving the already open file temporarily, and running the OpenXML stuff on temp file and somehow reconcile that with the existing doc using the Office API. Haven't thought this approach through, but it's not the ideal way I'd want to do it.

I also know of a property on the Word API that returns an XML string by doing Word.Range.XML. However, I'm unsure how to load this string value to the SDK so I can leverage its methods to help me.

like image 997
Shark Avatar asked Mar 28 '12 02:03

Shark


2 Answers

You can open word document Open XML SDK with file already open by office. You should open a FileStream at first and then open word document specifying this stream. Here is an example:

using (Stream stream = new FileStream(file,FileMode.Open,FileAccess.Read,FileShare.ReadWrite))
{
 using (WordprocessingDocument wpd = WordprocessingDocument.Open(stream, false))
 {
  ....
 }
}
like image 127
user1081783 Avatar answered Sep 22 '22 22:09

user1081783


Word Add-in along with Open Xml SDK seems to meet your requirement. You can find a sample @ http://blogs.msdn.com/b/atverma/archive/2012/01/11/utility-to-generate-word-documents-from-templates-using-visual-studio-2010-and-open-xml-2-0-sdk-part-3.aspx

like image 37
Atul Verma Avatar answered Sep 22 '22 22:09

Atul Verma