How To Add New Rows To An Existing Word Document Table In C#


Microsoft Word is a versatile tool used to create various documents, whether starting from a blank page or utilizing predefined templates similar to other Microsoft applications.

With MS Word, you can craft professional resumes, cover letters, flyers, and more. Additionally, it's suitable for creating certificates, to-do lists, or simply typing regular text for any official or documentation purposes. Hence, I've written this article for developers who are working with Word documents.

In this article, I'll explain how to add new rows to an existing table within a Word document using C#. To demonstrate, I've prepared a Word Document template featuring a table containing columns for Id, Name, Address, and Zipcode, as depicted in the image below.

 

TableWordTemplate

I have created a windows project for explain

Replace table

Below is customer.cs class file for creating the list which we insert in the word document.

public class Customer
    {
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string ZipCode { get; set; }
    }

Fill existing table in microsoft word dynamically via c#

OnClick of button copy paste the below doe

Step 1: Install open XML Nuget package

Install-Package DocumentFormat.OpenXml -Version 2.15.0

Step 2:Write Code

Now we going to insert new rows on the existing customer table using the C# .I’m using OpenXml for working with word documents for adding dynamic rows to the table. First, we are going to list all the tables inside our document identify if the table inside my word document template exists or not.

we are performing the  Add rows to a table dynamically in existing word document using OpenXml as you can see in below code. we are iterating through each customer in the list and adding it to the existing table.

if you are also looking for replacing text in the word file then please read below article

 private void button3_Click(object sender, EventArgs e)
        {
// original template path
var inputFile = @"E:\Template_table.docx";
//modify template path where we save modify word template
var outputFile = @"E:\ModifyTemplate_table.docx";

//creating customer list
            List<Customer> customerlist = new List<Customer>();
            customerlist.Add(new Customer { Id = 1, Name = "Blondel", Address = "Berguvsvägen", ZipCode = "68306" });
            customerlist.Add(new Customer { Id = 1, Name = "Chop", Address = "Heerstr. 22", ZipCode = "3434" });
            customerlist.Add(new Customer { Id = 1, Name = "Martine", Address = "Orchestra Terrace", ZipCode = "32232" });
            customerlist.Add(new Customer { Id = 1, Name = "Manuel", Address = "C/ Romero", ZipCode = "323323" });

//check if file exist or not
if (System.IO.File.Exists(inputFile))
            {
                WordDocumentService wordDocumentService = new WordDocumentService();
if (System.IO.File.Exists(inputFile))
                {
using (WordprocessingDocument doc = WordprocessingDocument.Open(inputFile, true)) //open source word file
                    {
                        Document document = doc.MainDocumentPart.Document;
                        OpenXmlPackage res = doc.SaveAs(outputFile); // copy it to outfile path for editing
                        res.Close();
                    }
using (WordprocessingDocument wordDoc2 = WordprocessingDocument.Open(outputFile, true))
                    {
var doc = wordDoc2.MainDocumentPart.Document;
//getting first table in word document specify as we use at zero index ElementAt(0)
                        DocumentFormat.OpenXml.Wordprocessing.Table table = doc.MainDocumentPart.Document.Body.Elements<DocumentFormat.OpenXml.Wordprocessing.Table>().ElementAt(0);
//iterating throgh each customer in the list and adding in the table
foreach (var item in customerlist)
                        {
                            DocumentFormat.OpenXml.Wordprocessing.TableRow tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
                            DocumentFormat.OpenXml.Wordprocessing.TableCell tablecellService1 = new DocumentFormat.OpenXml.Wordprocessing.TableCell(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(item.Id.ToString()))));
                            DocumentFormat.OpenXml.Wordprocessing.TableCell tablecellService2 = new DocumentFormat.OpenXml.Wordprocessing.TableCell(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(item.Name))));
                            DocumentFormat.OpenXml.Wordprocessing.TableCell tablecellService3 = new DocumentFormat.OpenXml.Wordprocessing.TableCell(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(item.Address))));
                            DocumentFormat.OpenXml.Wordprocessing.TableCell tablecellService4 = new DocumentFormat.OpenXml.Wordprocessing.TableCell(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(item.ZipCode))));
                            tr.Append(tablecellService1, tablecellService2, tablecellService3, tablecellService4);
                            table.AppendChild(tr);
                        }
                    }
                }
            }
        }

OutPut Word Document

Reseult of table insert

* if you have a question please comment

  • Original Template Path: the path to the original Word document template file (Template_table.docx) stored on the local file system.
  • Modified Template Path:  the path where the modified Word document template file (ModifyTemplate_table.docx) will be saved after making changes.
  • Creating Customer List: A list named customerlist is created to hold instances of the Customer class. Each Customer object represents a customer with properties like Id, Name, Address, and ZipCode.
  • Check if File Exists: This if statement checks if the original template file exists at the specified path before proceeding with any operations.
  • WordDocumentService Initialization: An instance of the WordDocumentService class is created to utilize its methods for modifying the Word document.
  • Open Original Word Document: The original Word document (Template_table.docx) is opened for editing using the WordprocessingDocument.Open method. It's opened in write mode (true).
  • Save Copy of Original Document: The original document is saved as a copy to the specified output file path (ModifyTemplate_table.docx). This is done using the SaveAs method of WordprocessingDocument, and the resulting package is stored in the res variable.
  • Close Original Document: The original document (Template_table.docx) is closed using the Close method on the res package.
  • Open Modified Word Document: The copied Word document (ModifyTemplate_table.docx) is opened for further modification using the WordprocessingDocument.Open method.
  • Get First Table: The first table in the Word document is retrieved using the Elements property of the Document.Body. This assumes that the table is located at index zero.
  • Iterate Through Customer List: A loop iterates through each Customer object in the customerlist and adds a new row to the table for each customer. It creates table cells for each property of the customer and appends them to a new table row (tr). Finally, it appends the new row to the table.

This code shows you how to open an original Word document template, add new rows to an existing table within it, and save the modified version to a new file. It utilizes the WordDocumentService class to handle the modification process efficiently.

Benefit of using Word Document in you Application

1. WYSIWYG (what-you-see-is-what-you-get) display: It ensures that whatever is displayed on the screen or appears on the screen when printed or in any other device When it is moved, it appears exactly as if it was the first one.

2. Spell check: Word has a built-in dictionary to check to spell; Any misspelled words are marked with a red squiggly underline. Word automatically auto-corrects the obviously misspelled word text or phrase in document.

5. External support: Word is very compatible with other programs to use, which have very common with other members of the Office suite.

With the help of MS Word, we can create a resume, write a letter, design a wedding card, write a notice, and we can do many other things.
MS Word is a computer application program developed by Microsoft.

With the help of Ms word, we can create any type of document and after editing it, we can do its formatting by opening it and viewing it and we can also share that document.