In this blog you will see how to add a simple table to the word processing document using Open XML SDK 2.0
Assembly:
DocumentFormat.OpenXml.dll
Namesapces:
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing; using System; using System.Collections.Generic; using System.Linq; using System.Text; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System.IO.Packaging; namespace OpenXMLConsole { class Program { static void Main(string[] args) { string path = @"E:\OpenXMLTable.docx"; //// Creates the new instance of the WordprocessingDocument class from the specified file //// WordprocessingDocument.Open(String, Boolean) method //// Parameters: //// string path - path is a string which contains the path of the document //// bool isEditable using (WordprocessingDocument doc = WordprocessingDocument.Create(path, WordprocessingDocumentType.Document)) { //// Defines the MainDocumentPart MainDocumentPart mainDocumentPart = doc.AddMainDocumentPart(); mainDocumentPart.Document = new Document(); Body body = mainDocumentPart.Document.AppendChild(new Body()); //// Create a new table Table tbl = new Table(); //// Create a new row TableRow tr = new TableRow(); //// Add a cell to each column in the row TableCell tcName1 = new TableCell(new Paragraph(new Run(new Text("Vijai")))); TableCell tcId1 = new TableCell(new Paragraph(new Run(new Text("1")))); //// Add the cells to the row tr.Append(tcName1, tcId1); // Create a new row TableRow tr1 = new TableRow(); TableCell tcName2= new TableCell(new Paragraph(new Run(new Text("Anand")))); TableCell tcId2 = new TableCell(new Paragraph(new Run(new Text("2")))); //// Add the cells to the row tr1.Append(tcName2, tcId2); //// Add the rows to the table tbl.AppendChild(tr); tbl.AppendChild(tr1); //// Add the table to the body body.AppendChild(tbl); mainDocumentPart.Document.Save(); } } } } <?xml version="1.0" encoding="utf-8"?> <w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"> <w:body> <w:tbl> <w:tr> <w:tc> <w:p> <w:r> <w:t>Vijai</w:t> </w:r> </w:p> </w:tc> <w:tc> <w:p> <w:r> <w:t>1</w:t> </w:r> </w:p> </w:tc> </w:tr> <w:tr> <w:tc> <w:p> <w:r> <w:t>Anand</w:t> </w:r> </w:p> </w:tc> <w:tc> <w:p> <w:r> <w:t>2</w:t> </w:r> </w:p> </w:tc> </w:tr> </w:tbl> </w:body> </w:document>
Code:
XML:

Join the conversation! Your thoughts help the community grow.