Click here to Skip to main content
15,895,777 members
Articles / Productivity Apps and Services / Microsoft Office

Creation of a Word 2007 document using the Open XML Format SDK

Rate me:
Please Sign up or sign in to vote.
4.92/5 (24 votes)
24 May 2009CPOL5 min read 165.4K   4.7K   72  
A simple “getting started” article that shows the basis of creation of a Word 2007 (docx) document using the Open XML Format SDK 2.0 CTP.
using System;
using System.Diagnostics;
using System.Windows.Forms;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

//http://msdn.microsoft.com/en-us/library/dd440953.aspx  !!!
//http://blogs.msdn.com/ericwhite/archive/2008/09/06/announcing-the-first-ctp-of-open-xml-sdk-v2.aspx
//https://openxmldeveloper.org/archive/2008/09/16/3702.aspx
//http://msdn.microsoft.com/en-us/library/bb448854(office.14).aspx



namespace OpenXML_SDK_HelloWorld
{
  public partial class Form1 : Form
  {
    delegate void Createdocument(string documentFileName);
    public Form1()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      ShowSaveDialogAndCreateDocument(HelloWorld);
    }

    private void ShowSaveDialogAndCreateDocument(Createdocument my_Createdocument)
    {
      SaveFileDialog mySaveFileDialog = new SaveFileDialog();
      mySaveFileDialog.Filter = "Word 2007 file (DOCX)|*.docx";
      //save dialog display:
      if (mySaveFileDialog.ShowDialog() == DialogResult.OK)
      {
        //call creation of HellowWord document
        my_Createdocument(mySaveFileDialog.FileName);
        // let's open this deocument in Word:
        Process.Start(mySaveFileDialog.FileName);
      }
    }
    private void HelloWorld(string documentFileName)
    {
      // Create a Wordprocessing document. 
      using (WordprocessingDocument myDoc = WordprocessingDocument.Create(documentFileName, WordprocessingDocumentType.Document))
      {
        // Add a new main document part. 
        MainDocumentPart mainPart = myDoc.AddMainDocumentPart();
        //Create Document tree for simple document. 
        mainPart.Document = new Document();
        //Create Body (this element contains other elements that we want to include
        Body body = new Body();
        //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);
        body.Append(paragraph);
        mainPart.Document.Append(body);
        // Save changes to the main document part. 
        mainPart.Document.Save();
      }
    }
    //ciekawy: http://msdn.microsoft.com/en-us/library/cc850838(office.14).aspx
    private void HelloWorld_withStyle(string documentFileName)
    {
      // Create a Wordprocessing document. 
      using (WordprocessingDocument myDoc = WordprocessingDocument.Create(documentFileName, WordprocessingDocumentType.Document))
      {
        // Add a new main document part. 
        MainDocumentPart mainPart = myDoc.AddMainDocumentPart();

        //Add new style part 
        StyleDefinitionsPart stylePart = mainPart.AddNewPart<StyleDefinitionsPart>();
        // we have to set the properties
        RunProperties rPr = new RunProperties();
        Color color = new Color() { Val = "FF0000" }; // the color is red
        RunFonts rFont = new RunFonts();
        rFont.Ascii = "Arial"; // the font is Arial
        rPr.Append(color);
        rPr.Append(rFont);
        rPr.Append(new Bold()); // it is Bold
        rPr.Append(new FontSize() { Val = 28 }); //font size (in 1/72  of an inch) 
        //creation of a style
        Style style = new Style();
        style.StyleId = "MyHeading1"; //this is the ID of the style
        style.Append(new Name() { Val = "My Heading 1" }); //this is name
        style.Append(new BasedOn() { Val = "Heading1" }); // our style based on Normal style
        style.Append(new NextParagraphStyle() { Val = "Normal" }); // the next paragraph is Normal type
        style.Append(rPr);//we are adding properties previously defined
        // we have to add style that we have created to the StylePart
        stylePart.Styles = new Styles();
        stylePart.Styles.Append(style);
        stylePart.Styles.Save(); // we save the style part

        //Create Document tree for simple document. 
        mainPart.Document = new Document();
        //Create Body (this element contains other elements that we want to include
        Body body = new Body();
        //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);
        Paragraph heading = new Paragraph();
        Run heading_run = new Run();
        Text heading_text = new Text("This is Heading");
        ParagraphProperties heading_pPr = new ParagraphProperties();
        heading_pPr.ParagraphStyleId = new ParagraphStyleId() { Val = "MyHeading1" }; // we set the style
        heading.Append(heading_pPr);
        heading_run.Append(heading_text);
        heading.Append(heading_run);
        body.Append(heading);
        body.Append(paragraph);
        mainPart.Document.Append(body);
        // Save changes to the main document part. 
        mainPart.Document.Save();
      }
    }
public void HelloWorld_table(string docName)
{
  // Create a Wordprocessing document. 
  using (WordprocessingDocument myDoc = WordprocessingDocument.Create(docName, WordprocessingDocumentType.Document))
  {
    // Add a new main document part. 
    MainDocumentPart mainPart = myDoc.AddMainDocumentPart();
    //Create DOM tree for simple document. 
    mainPart.Document = new Document();
    Body body = new Body();
    Table table = new Table();
    TableProperties tblPr = new TableProperties();
    TableBorders tblBorders = new TableBorders();
    tblBorders.TopBorder = new TopBorder();
    tblBorders.TopBorder.Val = new EnumValue<BorderValues>(BorderValues.Single);
    tblBorders.BottomBorder = new BottomBorder();
    tblBorders.BottomBorder.Val =new EnumValue<BorderValues>(  BorderValues.Single);
    tblBorders.LeftBorder = new LeftBorder();
    tblBorders.LeftBorder.Val = new EnumValue<BorderValues>(BorderValues.Single);
    tblBorders.RightBorder = new RightBorder();
    tblBorders.RightBorder.Val = new EnumValue<BorderValues>(BorderValues.Single);
    tblBorders.InsideHorizontalBorder = new InsideHorizontalBorder();
    tblBorders.InsideHorizontalBorder.Val = BorderValues.Single;
    tblBorders.InsideVerticalBorder = new InsideVerticalBorder();
    tblBorders.InsideVerticalBorder.Val = BorderValues.Single;
    tblPr.Append(tblBorders);
    table.Append(tblPr);
    TableRow tr;
    TableCell tc;
    //first row - title
    tr = new TableRow();
    tc = new TableCell(new Paragraph(new Run(new Text("Multiplication table"))));
    TableCellProperties tcp=new TableCellProperties();
    GridSpan gridSpan=new GridSpan();
    gridSpan.Val=11;
    tcp.Append(gridSpan);
    tc.Append(tcp);
    tr.Append(tc);
    table.Append(tr);
    //second row 
    tr = new TableRow();
    tc = new TableCell();
    tc.Append(new Paragraph(new Run(new Text("*"))));
    tr.Append(tc);
    for (int i = 1; i <= 10; i++)
    {
      tr.Append(new TableCell(new Paragraph(new Run(new Text(i.ToString())))));
    }
    table.Append(tr);
    for (int i = 1; i <= 10; i++)
    {
      tr = new TableRow();
      tr.Append(new TableCell(new Paragraph(new Run(new Text(i.ToString())))));
      for (int j = 1; j <= 10; j++)
      {
        tr.Append(new TableCell(new Paragraph(new Run(new Text((i*j).ToString())))));
      }
      table.Append(tr);
    }
    //appending table to body
    body.Append(table);
    // and body to the document
    mainPart.Document.Append(body);
    // Save changes to the main document part. 
    mainPart.Document.Save();
  }
}
    public void HelloWorld_table_simple(string docName)
    {
      // Create a Wordprocessing document. 
      using (WordprocessingDocument myDoc = WordprocessingDocument.Create(docName, WordprocessingDocumentType.Document))
      {
        // Add a new main document part. 
        MainDocumentPart mainPart = myDoc.AddMainDocumentPart();
        //Create DOM tree for simple document. 
        mainPart.Document = new Document();
        Body body = new Body();
        Table table = new Table(new TableRow(new TableCell(new Paragraph(new Run(new Text("Hello World!"))))));
        body.Append(table);
        //mainPart.Document.Append(h);
        mainPart.Document.Append(body);
        // Save changes to the main document part. 
        mainPart.Document.Save();

      }
    }
    private void button_helloworldwithstyles_Click(object sender, EventArgs e)
    {
      ShowSaveDialogAndCreateDocument(HelloWorld_withStyle);

    }
    private void button_sampletable_Click(object sender, EventArgs e)
    {
      ShowSaveDialogAndCreateDocument(HelloWorld_table);
    }

    private void button_thesimplesttable_Click(object sender, EventArgs e)
    {
      ShowSaveDialogAndCreateDocument(HelloWorld_table_simple);
    }

  }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Poland Poland

I am software developer and architect. I am interested in real-time systems programming, communication systems and new technologies.


For readers from Poland I suggest to visit my blog: http://maciej-progtech.blogspot.com/ to find interesting resources.


Comments and Discussions