文档星空最火知名网站>>Spire.Doc系列教程>>Word .NET库组件Spire.Doc系列教程(40):插入表格到Word文本框及获取和删除表格
Word .NET库组件Spire.Doc系列教程(40):插入表格到Word文本框及获取和删除表格
Spire.Doc for .NET是一个专业的Word .NET库,设计用于帮助开发人员高效地开发创建、阅读、编写、转换和打印任何来自.NET( C#, VB.NET, ASP.NET)平台的Word文档文件的功能。
本系列教程将为大家带来Spire.Doc for .NET在使用过程中的各类实际操作,word文档中经常会使用脚注和尾注来为文档添加说明。本文主要描述如何插入表格到Word文本框及获取和删除其中的表格。
11月优惠进行时,消费满额即享折上豪礼,想买Spire.Doc的朋友赶快吧!
推荐阅读:【想要快速完成文档格式转换吗?Spire系列组件格式转换完整攻略来啦!】
C# 插入表格到 Word 文本框以及获取和删除 Word 文本框中的表格
在Word中,文本框可以包含很多种元素,例如文本、图片和表格等。本文主要介绍如何使用Spire.Doc组件插入表格到Word文本框,以及获取和删除Word文本框中的表格。
插入表格
//创建Document实例
Document document = new Document();
//添加节
Section section = document.AddSection();
//添加段落
Paragraph paragraph = section.AddParagraph();
//添加文本框到段落,并指定文本框的宽度和高度
TextBox textbox = paragraph.AppendTextBox(300, 100);
//添加文本到文本框
Paragraph textboxParagraph = textbox.Body.AddParagraph();
TextRange textboxRange = textboxParagraph.AppendText("Table 1");
textboxRange.CharacterFormat.FontName = "Arial";
//插入表格到文本框
Table table = textbox.Body.AddTable(true);
//指定表格的行数和列数
table.ResetCells(4, 4);
string[,] data = new string[,]
{
{"姓名","年龄","性别","工号" },
{"张三","28","男","0023" },
{"李四","30","男","0024" },
{"王五","26","女","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.LightGridAccent3);
//保存文档
document.SaveToFile("AddTable.docx", FileFormat.Docx2013);
获取表格
//载入Word文档
Document document = new Document("AddTable.docx");
//获取第一个文本框
TextBox textbox = document.TextBoxes[0];
//获取文本框中第一个表格
Table table = textbox.Body.Tables[0] as Table;
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());
删除表格
//创建Document实例
Document document = new Document("AddTable.docx");
//获取第一个文本框
TextBox textbox = document.TextBoxes[0];
//删除文本框中第一个表格
textbox.Body.Tables.RemoveAt(0);
//保存文档
document.SaveToFile("RemoveTable.docx", FileFormat.Docx2013);

QQ交谈
在线咨询

渝公网安备
50010702500608号

客服热线