Open XML 1


Open XML Tricks:-

The first thing to do is the add reference to the Open XML library we are going to use.
If you are using Visual Studio 2008, you should use Open XML 2.0 Library as 2.5 the latest one is not supported by the Visual Studio 2008. If you are using higher version then you can try to add reference to Open XML 2.5 Library.

But any the commands and tricks given here will apply the same on these both versions of Open XML Library whether it is 2.0 or 2.5.

After adding reference to the Open XML Library we can use below lines on the top of our class file.


using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;


The first and the foremost command is to open the document through Open XML

WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true);

The filepath is the complete full file path of the file e.g. "C:\docs\mydoc.docx". Here I think I need not mention that backslash must be escaped or use Verbatim strings instead. The second parameter is the flag which lets you save the edits if it is true otherwise the changes will not be saved i.e. the document will be open in read only mode. If the flag is false, the surprise for you will be that no error will be generated during document editing, the only thing that will happen is that the changes will not be saved at all, and you'll wonder why that didn't happen.

Once document has been opened you can process it as you wish but in the end don't forget to close it.

doc.Close();

Or alternatively you can use the popular method instead as given below

using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
{
    // your code goes here
}



Comments

Popular posts from this blog

Privacy Policy