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); } } }