How to Add tables to word processing documents

  • OpenXML SDK
  • Spire.Doc
  • Download Sample Code

class Program
    {
        static void Main(string[] args)
        {
            string fileName = "Word10.docx";
            CreateTable(fileName);
        }
        // Insert a table into a word processing document.
        public static void CreateTable(string fileName)
        {
            using (WordprocessingDocument doc = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
            {
                MainDocumentPart mainPart = doc.AddMainDocumentPart();
                mainPart.Document = new Document();
                Body body = mainPart.Document.AppendChild(new Body());
                Table tb = new Table();
                TableRow row = new TableRow();
                TableCell cel = new TableCell(new Paragraph(new Run(new Text("OpenXML"))));
                row.AppendChild(cel);
                tb.AppendChild(row);
                body.Append(tb);
            }
        }

  class Program
    {
        static void Main(string[] args)
        {
            string fileName = "Word10.docx";
            CreateTable(fileName);
        }
        public static void CreateTable(string fileName)
        {
            Document document = new Document();
            Section section = document.AddSection();
            Table table = section.AddTable();
            table.ResetCells(1, 1);
            Documents.Paragraph para = table.Rows[0].Cells[0].AddParagraph();
            para.AppendText("SpireDoc");
            document.SaveToFile(fileName,FileFormat.Docx);
        }
    }