Adding Tables to Word Using OpenXML SDK

To use the code from the Open XML SDK 2.0, you must add several references to your project. The sample project already includes these references, but in your own code, you would have to explicitly reference the following assemblies:
  • WindowsBase - This reference may be set for you, depending on the kind of project that you create.
  • DocumentFormat.OpenXml - Installed by the Open XML SDK 2.0.
In addition, you should add the following using/Imports statements to the top of your code file.
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
Create a procedure "AddTable" which accepts two parameters "filename,data". This is how you'll pass the data to the function
const string fileName = @"C:\temp\AddTable.docx";
AddTable(fileName, new string[,] 
  { { "Texas", "TX" }, 
     { "California", "CA" }, 
     { "New York", "NY" }, 
     { "Massachusetts", "MA" } });
  • Method Description
public static void AddTable(string fileName, string[,] data)
{
  using (var document = WordprocessingDocument.Open(fileName, true))
  {

    var doc = document.MainDocumentPart.Document;

    Table table = new Table();

    TableProperties props = new TableProperties(
      new TableBorders(
        new TopBorder
        {
          Val = new EnumValue<BorderValues>(BorderValues.Single),
          Size = 12
        },
        new BottomBorder
        {
          Val = new EnumValue<BorderValues>(BorderValues.Single),
          Size = 12
        },
        new LeftBorder
        {
          Val = new EnumValue<BorderValues>(BorderValues.Single),
          Size = 12
        },
        new RightBorder
        {
          Val = new EnumValue<BorderValues>(BorderValues.Single),
          Size = 12
        },
        new InsideHorizontalBorder
        {
          Val = new EnumValue<BorderValues>(BorderValues.Single),
          Size = 12
        },
        new InsideVerticalBorder
        {
          Val = new EnumValue<BorderValues>(BorderValues.Single),
          Size = 12
        }));
    table.AppendChild<TableProperties>(props);

    for (var i = 0; i <= data.GetUpperBound(0); i++)
    {
      var tr = new TableRow();
      for (var j = 0; j <= data.GetUpperBound(1); j++)
      {
        var tc = new TableCell();
        tc.Append(new Paragraph(new Run(new Text(data[i, j]))));
        // Assume you want columns that are automatically sized.
        tc.Append(new TableCellProperties(
          new TableCellWidth { Type = TableWidthUnitValues.Auto }));
        tr.Append(tc);
      }
      table.Append(tr);
    }
    doc.Body.Append(table);
    doc.Save();
  }
}

Last edited Dec 10, 2013 at 10:17 AM by assadmahmood, version 1