sobota, 5 września 2009

Modification of the content of the DOCX document (part 1: Getting started) [EN]

kick it on DotNetKicks.comShout it

The Open XML Format SDK supports not only the creation of the new document but allows also the modification of the existing document. In this short article I want to present the short overview of how to do it.

Suppose we want to add new paragraph (that contains "Hello World! ") at the end of the existing document. The example function that is responsible for creation of such paragraph is presented below:

private Paragraph CreateAndReturnHelloWorldParagraph()
{
   //Create paragraph
   Paragraph paragraph = new Paragraph();
   Run run_paragraph = new Run();
   // we want to put that text into the output document
   Text text_paragraph = new Text( "Hello World!" );
   //Append elements appropriately.
   run_paragraph.Append( text_paragraph );
   paragraph.Append( run_paragraph );
   return paragraph;
}

Now let’s add a new "Hello World" paragraph at the end of the existing document.

First of all we have to open an existing document. To do it we can utilize the "WordprocessingDocument.Open" function. The first argument is the file name and the second argument is read/write mode. Because we want to modify the document, make sure that the read/mode mode is set to "true".

Note: make sure that the document that we are openning is closed and not opened by any application (e.g. Word editor). If it is opened the System.IO.IOException will be throwed ("The process cannot access the file XXX.docx' because it is being used by another process.").

Secondly we have to append the new paragraph to the body of the opened document (element: myWordprocessingDocument.MainDocumentPart.Document.Body)

The last step is saving of the modified document.

It is quite easy, am I right?

Finally the code of the function that modifies the docx document:

//Selecting a file
OpenFileDialog myopenFileDialog = new OpenFileDialog();
myopenFileDialog.Filter = "Word 2007 file (DOCX)|*.docx";
if ( myopenFileDialog.ShowDialog() == DialogResult.OK )
{
  //Open and manipulate docx
  using ( WordprocessingDocument myDoc = WordprocessingDocument.Open( myopenFileDialog.FileName, true ) )
  {
    //Access main part of document. 
    MainDocumentPart mainDocumentPart = myDoc.MainDocumentPart;
    //Creation of the new "hello world" paragraph
    Paragraph newelloWorldParagraph = CreateAndReturnHelloWorldParagraph();
    //Add new paragraph at the end of document body
    mainDocumentPart.Document.Body.Append( newelloWorldParagraph );
    //save the document
    mainDocumentPart.Document.Save();
  }
}
kick it on DotNetKicks.comShout it

Brak komentarzy:

Prześlij komentarz

Posty powiązane / Related posts