Word控件Spire.Doc 【Table】教程(9): 通过在 C# 中克隆来插入现有表

本文主要介绍如何通过在 C# 中克隆来插入现有表,欢迎查阅

在某些情况下,我们需要对现有表进行一些修改,但又不想破坏原始数据,因此我们希望复制现有表,然后在新表中进行一些更改。我们如何获得复制的表格简单的方法是克隆。将引入一个解决方案来复制表并修改一些数据,然后通过 Spire.Doc 在原始表之后插入新表。

Spire.Doc for .NET是一个独立的 .NET Word 组件,它提供了一种方法 Table.clone() 以允许用户复制现有表格。

解决的主要步骤:

首先:加载带有表格的word文档。

Document doc = new Document();doc.LoadFromFile(@"CopyTable.doc");

原文档效果截图:

通过克隆插入现有表

其次:提取现有表并调用table.clone()方法复制它。

Section se = doc.Sections[0];Table original_Table =(Table) se.Tables[0];Table copied_Table = original_Table.Clone();

再次:提取最后一行然后遍历其单元格以修改数据。

string[] st = new string[] { "Guyana", "Georgetown", "South America", "214969", "800000" };//get the last row of copied tableTableRow 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];}

最后调用 Section. tables.add() 方法将复制的表格添加到节中并保存此文档。

se.Tables.Add(copied_Table);doc.SaveToFile("result.doc", FileFormat.Doc);The result document effect screenshot:

通过克隆插入现有表

完整代码:

using Spire.Doc;using System.Drawing;namespace InsertingaAnExistingTable{class Program{static void Main(string[] args){//load a word documentDocument doc = new Document();doc.LoadFromFile(@"CopyTable.doc");// extract the existing tableSection 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 tableTableRow 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 sectionse.Tables.Add(copied_Table);doc.SaveToFile("result.doc", FileFormat.Doc);}}}

以上便是 如何 通过在 C# 中克隆来插入现有表,如果您有其他问题也可以继续浏览本系列文章,获取相关教程,你还可以给我留言或者加入我们的官方技术交流群。


欢迎下载|体验更多E-iceblue产品

获取更多信息请咨询在线客服  


标签:

来源:慧都

声明:本站部分文章及图片转载于互联网,内容版权归原作者所有,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!

上一篇 2023年1月25日
下一篇 2023年1月26日

相关推荐

发表回复

登录后才能评论