C# 操作Word文本框——插入、读取、删除表格

2025-07-06 15:16:31

常见的,我们在文本框中可以添文字、图片等元素,并设置文本或者文本框格式等等。对于一些需要在文本框中插入表格的要求,我们也是可以实现的。下面,将介绍如何在C#中添加、读取、删除表格到Word文本框中。

工具/原料

Free Spire.Doc for .NET 6.3 (免费版)

Visual Stuido

插入表格到文本框

1、【C#】using Spire.Doc;using Spire.Doc.Documents;using Spire.Doc.Fields;namespace InsertTableToTextbox_Doc{ class Program { static void Main(string[] args) { //创建一个Document类对象 Document document = new Document(); //添加section到文档 Section section = document.AddSection(); //添加段落section Paragraph paragraph = section.AddParagraph(); //添加指定大小的文本框到段落 TextBox textbox = paragraph.AppendTextBox(300, 100); //添加文本到文本,设置文本格式 Paragraph textboxParagraph = textbox.Body.AddParagraph(); TextRange textboxRange = textboxParagraph.AppendText("Sample Report 1"); textboxRange.CharacterFormat.FontName = "Arial"; //插入表格到文本框 Table table = textbox.Body.AddTable(true); //指定表格行数、列数 table.ResetCells(4, 4); //实例化数组内容 string[,] data = new string[,] { {"Name","Age","Gender","ID" }, {"John","28","Male","0023" }, {"Steve","30","Male","0024" }, {"Lucy","26","female","0025" } }; //将数组内容添加到表格 for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { TextRange tableRange = table[i, j].AddParagraph().AppendText(data[i, j]); tableRange.CharacterFormat.FontName = "Arial"; } } //应用表格样式 table.ApplyStyle(DefaultTableStyle.MediumGrid3Accent1); //保存并打开文档 document.SaveToFile("Output.docx", FileFormat.Docx2013); System.Diagnostics.Process.Start("Output.docx"); } }}

C# 操作Word文本框——插入、读取、删除表格

读取文本框中的表格

1、【C#】using Spire.Doc;using Spire.Doc.Documents;using Spire.Doc.Fields;using System.IO;using System.Text;namespace GetTableFromTextbox_Doc{ class Program { static void Main(string[] args) { //载入Word文档 Document document = new Document("Output.docx"); //获取第一个文本框 TextBox textbox = document.TextBoxes[0]; //获取文本框中第一个表格 Table table = textbox.Body.Tables[0] as Table; //实例化StringBuilder类 StringBuilder sb = new StringBuilder(); //遍历表格中的段落并提取文本 foreach (TableRow row in table.Rows) { foreach (TableCell cell in row.Cells) { foreach (Paragraph paragraph in cell.Paragraphs) { sb.AppendLine(paragraph.Text); } } } File.WriteAllText("text.txt", sb.ToString()); } }}

C# 操作Word文本框——插入、读取、删除表格

删除文本框中的表格

1、【C#】using Spire.Doc;using Spire.Doc.Fields;namespace RemoveTableFormTextbox_Doc{ class Program { static void Main(string[] args) { //创建Document实例 Document document = new Document("Output.docx"); //获取第一个文本框 TextBox textbox = document.TextBoxes[0]; //删除文本框中第一个表格 textbox.Body.Tables.RemoveAt(0); //保存文档 document.SaveToFile("RemoveTable.docx", FileFormat.Docx2013); System.Diagnostics.Process.Start("RemoveTable.docx"); } }}

注:

1、这里应用表格格式,Spire.Doc 支持多种不同的表格类型,可根据需要自行选择。

C# 操作Word文本框——插入、读取、删除表格
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢