Table (22)
In some case, we need make some modifications in an existing table but don't want destroy the original data, so we would like to copy the existing table then make some changes in the new table. How could we get the copied table? The easiest method is clone. There would introduce a solution to copy table and modify some data then insert the new table after original table via Spire.Doc.
Spire.Doc for .NET, a stand-alone .NET Word component, provides a method, Table.clone() to allow users to copy an existing table.
The main steps of the solution:
Firstly: load the word document with a table.
Document doc = new Document(); doc.LoadFromFile(@"CopyTable.doc");
The original document effect screenshot:

Secondly: extract the existing table and call the table.clone () method to copy it.
Section se = doc.Sections[0]; Table original_Table =(Table) se.Tables[0]; Table copied_Table = original_Table.Clone();
Thirdly: extract the last row then traversal its cells to modify data.
string[] st = new string[] { "Guyana", "Georgetown", "South America", "214969", "800000" };
//get the last row of copied table
TableRow lastRow = copied_Table.Rows[copied_Table.Rows.Count - 1];
//change lastRow data.
lastRow.RowFormat.BackColor = Color.Gray;
for (int i = 0; i < lastRow.Cells.Count; i++)
{
lastRow.Cells[i].Paragraphs[0].Text = st[i];
}
Finally: call Section. tables.add() method to add the copied table in section and save this document.
se.Tables.Add(copied_Table);
doc.SaveToFile("result.doc", FileFormat.Doc);
The result document effect screenshot:

Full code:
using Spire.Doc;
using System.Drawing;
namespace InsertingaAnExistingTable
{
class Program
{
static void Main(string[] args)
{
//load a word document
Document doc = new Document();
doc.LoadFromFile(@"CopyTable.doc");
// extract the existing table
Section se = doc.Sections[0];
Table original_Table =(Table) se.Tables[0];
// copy the existing table to copied_Table via Table.clone()
Table copied_Table = original_Table.Clone();
string[] st = new string[] { "Guyana", "Georgetown", "South America", "214969", "800000" };
//get the last row of table
TableRow lastRow = copied_Table.Rows[copied_Table.Rows.Count - 1];
//change last row data.
lastRow.RowFormat.BackColor = Color.Gray;
for (int i = 0; i < lastRow.Cells.Count; i++)
{
lastRow.Cells[i].Paragraphs[0].Text = st[i];
}
// add copied_Table in section
se.Tables.Add(copied_Table);
doc.SaveToFile("result.doc", FileFormat.Doc);
}
}
}
Apply Built-In Table Styles to Existing Word Tables in C#, VB.NET
2014-10-28 08:07:45 Written by KoohjiEvery time we create a plain table in a Word document, we may want to change the style of the table so as to make it more vivid and attractive. In our previous article, we have demonstrated how to set Word table formatting with custom style. However, if we do not have much time to do so, we can apply built-in table styles to own a better appearance within a few minutes. This article focuses on how to apply built-in table styles to existing Word tables using Spire.Doc with C#, VB.NET.
In the class of Spire.Doc.Table, it provides Table.ApplyStyle() method which enable us to easily change the layout of tables with default styles. As is shown below, here is a Word document that contains two plain tables in the first page. Let us see how we can format the table style with several lines of code.
Test File:

Code Snippet:
Step 1: Create a new Word document and load the test file.
Document doc = new Document("table.docx", FileFormat.Docx2010);
Step 2: Get the two tables from document.
Section section = doc.Sections[0]; Table table1 = section.Tables[0] as Table; Table table2 = section.Tables[1] as Table;
Step 3: Apply tables with built-in table styles separately.
table1.ApplyStyle(DefaultTableStyle.MediumShading1Accent2); table2.ApplyStyle(DefaultTableStyle.MediumShading2Accent1);
Step 4: Save the file.
doc.SaveToFile("result.docx", FileFormat.Docx);
Output:

Entire Code:
using Spire.Doc;
using Spire.Doc.Documents;
namespace ApplyTableStyles
{
class Program
{
static void Main(string[] args)
{
Document doc = new Document("table.docx", FileFormat.Docx2010);
Section section = doc.Sections[0];
Table table1 = section.Tables[0] as Table;
Table table2 = section.Tables[1] as Table;
table1.ApplyStyle(DefaultTableStyle.MediumShading1Accent2);
table2.ApplyStyle(DefaultTableStyle.MediumShading2Accent1);
doc.SaveToFile("result.docx", FileFormat.Docx);
}
}
}
Imports Spire.Doc
Imports Spire.Doc.Documents
Namespace ApplyTableStyles
Class Program
Private Shared Sub Main(args As String())
Dim doc As New Document("table.docx", FileFormat.Docx2010)
Dim section As Section = doc.Sections(0)
Dim table1 As Table = TryCast(section.Tables(0), Table)
Dim table2 As Table = TryCast(section.Tables(1), Table)
table1.ApplyStyle(DefaultTableStyle.MediumShading1Accent2)
table2.ApplyStyle(DefaultTableStyle.MediumShading2Accent1)
doc.SaveToFile("result.docx", FileFormat.Docx)
End Sub
End Class
End Namespace
Spire.Doc has a powerful function of processing word table such as create and remove word table, set the table column width, style and so on. Spire.Doc also supports to add the table in the middle of the word document. This article will show you how to replace text with table by finding the key text in the word document.
Download and install Spire.Doc for .NET and then add Spire.Doc.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Doc\Bin\NET4.0\ Spire.Doc.dll". Here comes to the details of how to finding the text and then replace it with table in C#.
Check the original word document at first:

Step 1: Create a new document and load from file.
Document doc = new Document();
doc.LoadFromFile("sample.docx");
Step 2: Find the place where you want to replace with table.
Section section = doc.Sections[0];
//"Fortune" as a "key text"
TextSelection selection = doc.FindString("Fortune", true, true);
TextRange range = selection.GetAsOneRange();
Paragraph paragraph = range.OwnerParagraph;
Body body = paragraph.OwnerTextBody;
int index = body.ChildObjects.IndexOf(paragraph);
Step 3: Add a table and set its style.
Table table = section.AddTable(true); table.ResetCells(3,3);
Step 4: Remove the paragraph and insert the table.
body.ChildObjects.Remove(paragraph); body.ChildObjects.Insert(index, table);
Step 5: Save the document to file.
doc.SaveToFile("Result.docx", FileFormat.Docx);
Effective screenshot of add a table in the middle of the word document by replacing the text.

Full codes:
namespace replaceTextwithTable
{
class Program
{
static void Main(string[] args)
{
Document doc = new Document();
doc.LoadFromFile("sample.docx");
Section section = doc.Sections[0];
TextSelection selection = doc.FindString("Fortune", true, true);
TextRange range = selection.GetAsOneRange();
Paragraph paragraph = range.OwnerParagraph;
Body body = paragraph.OwnerTextBody;
int index = body.ChildObjects.IndexOf(paragraph);
Table table = section.AddTable(true);
table.ResetCells(3,3);
body.ChildObjects.Remove(paragraph);
body.ChildObjects.Insert(index, table);
doc.SaveToFile("Result.docx", FileFormat.Docx);
}
}
}
Merging cells means combining two or more cells into one larger cell, while splitting cells means dividing one cell into two or more smaller cells. When creating or editing tables in Microsoft Word, you may often need to merge or split table cells in order to better present your data. In this article, you will learn how to merge or split table cells in a Word document in C# and VB.NET using Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Merge Table Cells in Word Using C# and VB.NET
In Microsoft Word, you can merge two or more adjacent cells horizontally or vertically into a larger cell. In Spire.Doc, you can achieve the same using the Table.ApplyHorizontalMerge() or Table.ApplyVerticalMerge() method. The following are the detailed steps:
- Initialize an instance of the Document class.
- Load a Word document using Document.LoadFromFile() method.
- Get a specific section in the document by its index through Document.Sections[int] property.
- Add a table to the section using Section.AddTable() method.
- Specify the number of rows and columns of the table using Table.ResetCells() method.
- Horizontally merge specific cells in the table using Table.ApplyHorizontalMerge() method.
- Vertically merge specific cells in the table using Table.ApplyVerticalMerge() method.
- Add some data to the table.
- Apply a style to the table.
- Save the result document using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
namespace MergeTableCells
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document document = new Document();
//Load a Word document
document.LoadFromFile("Input.docx");
//Get the first section
Section section = document.Sections[0];
//Add a 4 x 4 table to the section
Table table = section.AddTable();
table.ResetCells(4, 4);
//Horizontally merge cells 1, 2, 3, and 4 in the first row
table.ApplyHorizontalMerge(0, 0, 3);
//Vertically merge cells 3 and 4 in the first column
table.ApplyVerticalMerge(0, 2, 3);
//Add some data to the table
for (int row = 0; row < table.Rows.Count; row++)
{
for (int col = 0; col < table.Rows[row].Cells.Count; col++)
{
TableCell cell = table[row, col];
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle;
Paragraph paragraph = cell.AddParagraph();
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center;
paragraph.Text = "Text";
}
}
//Apply a style to the table
table.ApplyStyle(DefaultTableStyle.LightGridAccent1);
//Save the result document
document.SaveToFile("MergeCells.docx", FileFormat.Docx2013);
}
}
}

Split Table Cells in Word Using C# and VB.NET
Spire.Doc for .NET offers the TableCell.SplitCell() method that enables you to split a cell in a Word table into two or more cells. The following are the detailed steps:
- Initialize an instance of the Document class.
- Load a Word document using Document.LoadFromFile() method.
- Get a specific section in the document by its index through Document.Sections[int] property.
- Get a specific table in the section by its index through Section.Tables[int] property.
- Get the table cell that you want to split through Table.Rows[int].Cells[int] property.
- Split the cell into specific number of columns and rows using TableCell.SplitCell() method.
- Save the result document using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc;
namespace SplitTableCells
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document document = new Document();
//Load a Word Document
document.LoadFromFile("MergeCells.docx");
//Get the first section
Section section = document.Sections[0];
//Get the first table in the section
Table table = section.Tables[0] as Table;
//Get the 4th cell in the 4th row
TableCell cell1 = table.Rows[3].Cells[3];
//Split the cell into 2 columns and 2 rows
cell1.SplitCell(2, 2);
//save the result document
document.SaveToFile("SplitCells.docx", FileFormat.Docx2013);
}
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Tables in Word documents allow users to organize data in a structured, readable format. However, at times you may find that some tables are outdated or no longer serve their intended purpose, making it necessary to remove them. In this article, you will learn how to remove tables from a Word document in C# using Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Remove a Specified Table in Word in C#
Spire.Doc for .NET provides the Section.Tables.RemoveAt(int index) method to delete a specified table in a Word document by index. The following are the detailed steps.
- Create a Document instance.
- Load a Word document using Document.LoadFromFile() method.
- Get a specified section using Document.Sections[] property.
- Delete a specified table by index using Section.Tables.RemoveAt() method.
- Save the result document using Document.SaveToFile() method.
- C#
using Spire.Doc;
namespace RemoveTable
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document doc = new Document();
//Load a Word document
doc.LoadFromFile("tables.docx");
//Get the first section in the document
Section sec = doc.Sections[0];
//Remove the first table in the section
sec.Tables.RemoveAt(0);
//Save the result document
doc.SaveToFile("RemoveATable.docx", FileFormat.Docx);
}
}
}

Remove All Tables in Word in C#
To delete all tables from a Word document, you need to iterate through all sections in the document, then iterate through all tables in each section and remove them through the Section.Tables.Remove() method. The following are the detailed steps.
- Create a Document instance.
- Load a Word document using Document.LoadFromFile() method.
- Iterate through all sections in the document.
- Iterate through all tables in each section.
- Delete the tables using Section.Tables.Remove() method.
- Save the result document using Document.SaveToFile() method.
- C#
using Spire.Doc;
namespace RemoveAllTable
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document doc = new Document();
//Load a Word document
doc.LoadFromFile("tables.docx");
//Iterate through all sections in the document
foreach (Section section in doc.Sections)
{
//Iterate through all tables in each section
foreach (Table table in section.Tables)
{
//Remove the tables
section.Tables.Remove(table);
}
}
//Save the result document
doc.SaveToFile("RemoveTables.docx", FileFormat.Docx);
}
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Table in Microsoft Word is used to present data information which can assist to explain specified paragraph contents. In order to have a better appearance, people can set Word table style. This guide shows how to use Spire.Doc to set table style in Word with C#/VB.NET.
Download Spire.Doc (or Spire.Office) with .NET Framework 2.0 (or above) together. Once make sure Spire.Doc (or Spire.Office) are correctly installed on system, follow the steps below to set Word table style
In this example, a Word document with table has been prepared. It is a student transcript template from Office.com.
Step 1: Create a C#/VB.NET project in Visual Studio. Add Spire.Doc.dll as reference.
Document document = new Document(); document.LoadFromFile(@"E:\work\Documents\Student Transcript.docx");
Dim document As New Document()
document.LoadFromFile("E:\work\Documents\Student Transcript.docx")
Step 2: Set Table Style
Get table which you want to set style
Because table1 type is different from document.Sections[0].Tables[1] type, so use (Table) to transformed forcibly.
Table table1 = (Table)document.Sections[0].Tables[1];
Dim table1 As Table = CType(document.Sections(0).Tables(1), Table)
Set table row height.
table1.Rows[0].Height = 25;
table1.Rows(0).Height = 25
Set Table Style
In order to have distinction. Keep the first cell in first row as before and set style for the second cell. Firstly, set alignment and background color for the second cell. Secondly, declare a paragraph style, including font size, color and apply this style in cell.
table1.Rows[0].Cells[1].CellFormat.VerticalAlignment = VerticalAlignment.Middle; table1.Rows[0].Cells[1].CellFormat.BackColor = Color.LimeGreen; ParagraphStyle style = new ParagraphStyle(document); style.Name = "TableStyle"; style.CharacterFormat.FontSize = 14; style.CharacterFormat.TextColor = Color.GhostWhite; document.Styles.Add(style); table1.Rows[0].Cells[1].Paragraphs[0].ApplyStyle(style.Name);
table1.Rows(0).Cells(1).CellFormat.VerticalAlignment = VerticalAlignment.Middle table1.Rows(0).Cells(1).CellFormat.BackColor = Color.LimeGreen Dim style As New ParagraphStyle(document) style.Name = "TableStyle" style.CharacterFormat.FontSize = 14 style.CharacterFormat.TextColor = Color.GhostWhite document.Styles.Add(style) table1.Rows(0).Cells(1).Paragraphs(0).ApplyStyle(style.Name)
Step 3: Save and Launch
document.SaveToFile("WordTable.docx", FileFormat.Docx);
System.Diagnostics.Process.Start("WordTable.docx");
document.SaveToFile("WordTable.docx", FileFormat.Docx)
System.Diagnostics.Process.Start("WordTable.docx")
Effective Screenshot:

This guide shows how to set Word table style such as size and color via Spire.Doc. However, Spire.Doc can do a lot on operating Word document Click to learn more
By using Spire.Doc, developers can create Word document with a table inside (Click to learn how to create table in Word document). But when users create table in Word document, they would not only create table with blank cells. They need set formats or sometimes set table size like column width. This article will show you how to set Word table column width.
Make sure Spire.Doc and Visual Studio are correctly installed on system. Follow the simple steps below to set Word table column width.
Step 1: Create a C# windows form application in Visual Studio. Add Spire.Doc.dll as reference. The default setting of Spire.Doc.dll is placed under "C:\Program Files\e-iceblue\Spire.Doc\Bin". Select assembly Spire.Doc.dll and click OK to add it to the project.
using System;
using Spire.Doc;
using Spire.Doc.Fields;
using Spire.Doc.Documents;
namespace TableWidth
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}
Imports Spire.Doc Imports Spire.Doc.Fields Imports Spire.Doc.Documents Namespace TableWidth Public Partial Class Form1 Inherits Form Public Sub New() InitializeComponent() End Sub Private Sub button1_Click(sender As Object, e As EventArgs) End Sub End Class End Namespace
Step 2: Put the word document with table into the project folder. Use the following code to load it into project.
Document doc = new Document();
doc.LoadFromFile(@"..\..\Table.docx",FileFormat.Docx);
Dim doc As New Document()
doc.LoadFromFile("..\..\Table.docx", FileFormat.Docx)
Step 3: Because Spire.Doc doesn't have a direct method to set column width, we need set the first cell width of in each row.
for (int i = 0; i < document.Sections[0].Tables[0].Rows.Count; i++)
{
document.Sections[0].Tables[0].Rows[i].Cells[0].Width = 20;
}
For i As Integer = 0 To document.Sections(0).Tables(0).Rows.Count - 1 document.Sections(0).Tables(0).Rows(i).Cells(0).Width = 20 Next
Step 4: Save and Preview.
document.SaveToFile(@"..\..\Sample.docx",FileFormat.Docx);
document.SaveToFile("..\..\Sample.docx", FileFormat.Docx)
System.Diagnostics.Process.Start("..\..\Test.pdf")
Now, the whole process is finished. Press F5 and click the button to run the project. The generated docx file can be found at the project debug folder. Check the effect.
Before Setting Width:

After Setting Width:

As a professional and powerful Word component, Spire.Doc doesn't need Microsoft Office Word Automation but also allows user to directly operate Word document, format and style and insert content to Word document.Click to learn more feature functions of Spire.Doc
In MS Word, the tables can organize and present data in rows and columns, which makes the information easier to understand and analyze. In this article, you will learn how to programmatically create a table with data in a Word document using Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Create a Simple Table in Word
Below are some of the core classes and methods provided by Spire.Doc for .NET for creating and formatting tables in Word.
| Name | Description |
| Table Class | Represents a table in a Word document. |
| TableRow Class | Represents a row in a table. |
| TableCell Class | Represents a specific cell in a table. |
| Section.AddTbale() Method | Adds a new table to the specified section. |
| Table.ResetCells() Method | Resets row number and column number. |
| Table.Rows Property | Gets the table rows. |
| TableRow.Height Property | Sets the height of the specified row. |
| TableRow.Cells Property | Returns the cells collection. |
| TableRow.RowFormat Property | Gets the format of the specified row. |
The detailed steps are as follows
- Create a Document object and add a section to it.
- Prepare the data for the header row and other rows, storing them in a one-dimensional string array and a two-dimensional string array respectively.
- Add a table to the section using Section.AddTable() method.
- Insert data to the header row, and set the row formatting, including row height, background color, and text alignment.
- Insert data to the rest of the rows and apply formatting to these rows.
- Save the document to another file using Document.SaveToFile() method.
- C#
- VB.NET
using System;
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace WordTable
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document doc = new Document();
//Add a section
Section s = doc.AddSection();
//Define the data for the table
String[] Header = { "Date", "Description", "Country", "On Hands", "On Order" };
String[][] data = {
new String[]{ "08/07/2021","Dive kayak","United States","24","16"},
new String[]{ "08/07/2021","Underwater Diver Vehicle","United States","5","3"},
new String[]{ "08/07/2021","Regulator System","Czech Republic","165","216"},
new String[]{ "08/08/2021","Second Stage Regulator","United States","98","88"},
new String[]{ "08/08/2021","Personal Dive Sonar","United States","46","45"},
new String[]{ "08/09/2021","Compass Console Mount","United States","211","300"},
new String[]{ "08/09/2021","Regulator System","United Kingdom","166","100"},
new String[]{ "08/10/2021","Alternate Inflation Regulator","United Kingdom","47","43"},
};
//Add a table
Table table = s.AddTable(true);
table.ResetCells(data.Length + 1, Header.Length);
//Set the first row as table header
TableRow FRow = table.Rows[0];
FRow.IsHeader = true;
//Set the height and color of the first row
FRow.Height = 23;
FRow.RowFormat.BackColor = Color.LightSeaGreen;
for (int i = 0; i < Header.Length; i++)
{
//Set alignment for cells
Paragraph p = FRow.Cells[i].AddParagraph();
FRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
p.Format.HorizontalAlignment = HorizontalAlignment.Center;
//Set data format
TextRange TR = p.AppendText(Header[i]);
TR.CharacterFormat.FontName = "Calibri";
TR.CharacterFormat.FontSize = 12;
TR.CharacterFormat.Bold = true;
}
//Add data to the rest of rows and set cell format
for (int r = 0; r < data.Length; r++)
{
TableRow DataRow = table.Rows[r + 1];
DataRow.Height = 20;
for (int c = 0; c < data[r].Length; c++)
{
DataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
Paragraph p2 = DataRow.Cells[c].AddParagraph();
TextRange TR2 = p2.AppendText(data[r][c]);
p2.Format.HorizontalAlignment = HorizontalAlignment.Center;
//Set data format
TR2.CharacterFormat.FontName = "Calibri";
TR2.CharacterFormat.FontSize = 11;
}
}
//Save the document
doc.SaveToFile("WordTable.docx", FileFormat.Docx2013);
}
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.