在文本框中,我們可以操作很多元素,如文本、圖檔、表格等,在本篇文章中将着重介紹如何插入表格到文本框,插入的表格我們可以對表格進行格式化操作來豐富表格内容。此外,對于文本框中的表格内容,我們也可以根據需要來讀取表格或者删除表格。
使用工具
- Free Spire.Doc for .NET 6.3(免費版)
示例代碼
【示例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");
}
}
}
這裡應用表格格式,Spire.Doc 支援多種不同的表格類型,可根據需要自行選擇。

表格添加效果:
【示例2】讀取文本框中的表格
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());
}
}
}
讀取結果:
【示例3】删除Word文本框中的表格
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");
}
}
}
删除效果:
附:
除了添加在文本框彙中操作表格以外,我們向文本框中添加圖文混排的内容也是比較常見的,不僅僅隻是添加簡單文本或者圖檔,一些複雜的格式化的操作也是可以的,具體可以參閱部落格“C# 插入排版精良的Word文本框”
以上是本次關于“C# 操作Word 文本框中的表格”的全部内容。如需轉載,請注明出處!
感謝閱讀!