Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving an OpenXML Document (Word) generated from a template

I have a bit of code that will open a Word 2007 (docx) document and update the appropriate CustomXmlPart (thus updating the Content Controls in the document itself as they are mapped to the CustomXmlPart) but can't work out how to save this as a new file.! Surely it can't be that hard!

My current thinking is that I need to open the template and copy the content into a new, blank document - file by file, updating the CustomXmlPart when I encounter it. Call me old fashioned but that sounds a little bit clunky to me!

Why can't I just do a WordprocessingDocument.SaveAs(filename); ...?

Please tell me I am missing something simple here.

Thanks in advance

like image 621
DilbertDave Avatar asked Aug 05 '09 13:08

DilbertDave


3 Answers

OpenXml 2.8.1 has a SaveAs method that seems to do the trick.

var document = WordprocessingDocument.Open(specificationPath, true);
document.SaveAs("filePath/documentCopy.docx");
like image 163
bwall Avatar answered Oct 12 '22 22:10

bwall


Indeed you can, at least, in OpenXml SDK 2.5. However, watchout to work with a copy of the original file, because changes in the XML will be actually reflected in the file. Here you have the methods Load and Save of my custom class (after removing some validation code,...):

    public void Load(string pathToDocx)
    {
        _tempFilePath = CloneFileInTemp(pathToDocx);
        _document = WordprocessingDocument.Open(_tempFilePath, true);
        _documentElement = _document.MainDocumentPart.Document;
    }    

    public void Save(string pathToDocx)
    {
        using(FileStream fileStream = new FileStream(pathToDocx, FileMode.Create))
        {
            _document.MainDocumentPart.Document.Save(fileStream);
        }
    }

Having "_document" as a WordprocessingDocument instance.

like image 29
Héctor Espí Hernández Avatar answered Oct 13 '22 00:10

Héctor Espí Hernández


Are you referring to the OpenXml SDK? Unfortunately, as of OpenXml SDK 2.0, there's no SaveAs method. You'll need to:

  1. Make a temporary copy of your template file, naming it whatever you want.
  2. Perform your OpenXml changes on the above file.
  3. Save the appropriate sections (ie. using the .myWordDocument.MainDocumentPart.Document.Save() method for the main content or someHeaderPart.Header.Save() method for a particular header).
like image 42
Ahmad Mageed Avatar answered Oct 12 '22 22:10

Ahmad Mageed