As we know that MS Word is used to create documents Either it is blank at the start or it has a template that is similar to all other Microsoft applications.
Using MS Word, you can create many things like a professional resume, cover letters, flyers, and so on.Also, you can create certificates, to-do list.you can type normal words in the document. we can also do any official work or documentation work. So I decided to write this article for all developers who working on Word Document.
In this article, I will explain to you, How to add new rows to an existing word document table in C#. So, I have created a Word Document template with an existing table inside the word document which has Id, Name, address, and Zipcode column .As you can see in the below image.
I have created a windows project for explain
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
* if you have a question please comment
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.
The post How to add new rows to an existing word document table in C# appeared first on Software Development | Programming Tutorials.
Read More Articles
- Write a value which contain comma to a CSV file in c#?
- Reading CSV File with cells containing commas c#
- Split CSV with columns may contain ‘,’ Comma C#
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- [Simple Way]-ASP.NET Core Upload Multiple File Web API model
- [Simple Way]- Image Upload in .NET Core Web API
- [Easy Way]-Receive File and other form data together in ASP.NET Core Web API
- Replace image in word document using C#
- How to add new rows to an existing word document table in C#
- Add a row to an existing table in a Word Document (open XML)
- How to add items one at a time to to a new line a word document using word interop
- How to add a new row to an existing table using c# sql server
- How to add New Column with Value to the Existing DataTable?
- How do you add an existing form to a new project?
- How to dynamically add rows to a table in ASP.NET?
- Add Header and Footer to an existing empty word document with OpenXML SDK 2.0
- How to add a new counter to an existing performance counter category without deleting the old counters?
- When programmatically creating a new IIS web site, how can I add it to an existing application pool?
- How can i generate a word document docx with existing text as in a template, but fill in value thru a asp.net web form?
- Add new table to an existing database using database first approach EF
- How can I add and use new column in abpfeature table and access it in boilerplate?
- How to add new job or update the trigger for existing job in the Quartz.Net?
- How to add new ASP.NET table row by clicking button?
- Method to Add new or update existing item in Dictionary
- How to add a new row to datagridview programmatically
- How to add Web API to an existing ASP.NET MVC (5) Web Application project?
- Add new item in existing array in c#.net
- How to add new line into txt file
- How can I add a new column and data to a datatable that already contains data?
- How can a Word document be created in C#?
- How do I add my new User Control to the Toolbox or a new Winform?
- How do I iterate through rows in an excel table using epplus?
- How to get all rows in Azure table Storage in C#?
- How to add new DataRow into DataTable?
- how to add a new c# file to a project using dotnet-cli
- How do I add files to an existing zip archive
- How do I update an existing document inside ElasticSearch index using NEST?
- How to add existing project to Visual studio 2012 after renaming the project path
- How to add Web API controller to an existing ASP.NET Core MVC?
- Format number as text in CSV when open in both Excel and Notepad
- Embed Google Maps in C#
- What's the best way of achieving a parallel infinite Loop?
- Why is my XDocument saving the declaration when I don't want it to?
- Windows Store app - Sideloading & beta testing
- SetValue on PropertyInfo instance error "Object does not match target type" c#
- Check if a string contains one of 10 characters
- How to save ItemAttachments using EWS Managed API
- Authorize callback endpoint keeps redirecting to the user interaction login page IdentityServer
- Array of pointers in C++/CLI MSIL assembly
- Finding nearest sumElement combination in list
- How to convert an rtf string to text in C#
- C#: Adding extension methods to a base class so that they appear in derived classes
- How to Solve Max Connection Pool Error
- Why can't .Net / C# understand interface inheritance with properties of the same name?
- How Do You Communicate Service Layer Messages/Errors to Higher Layers Using MVP?
- How does the .NET Framework assign thread IDs?
- What is the purpose of :: in C#?
- How to set icon to subitem of listview using c#?
- Is this (volatile bool) always thread safe?