在文本框中,我們可以操作很多元素,如文本、圖片、表格等,在本篇文章中將着重介紹如何插入表格到文本框,插入的表格我們可以對表格進行格式化操作來豐富表格內容。此外,對於文本框中的表格內容,我們也可以根據需要來讀取表格或者刪除表格。
使用工具
示例代碼
【示例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】讀取文本框中的表格
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()); } } }
讀取結果:
【示例3】刪除Word文本框中的表格
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"); } } }
刪除效果:
附:
除了添加在文本框匯中操作表格以外,我們向文本框中添加圖文混排的內容也是比較常見的,不僅僅只是添加簡單文本或者圖片,一些復雜的格式化的操作也是可以的,具體可以參閱博客“C# 插入排版精良的Word文本框”
以上是本次關於“C# 操作Word 文本框中的表格”的全部內容。如需轉載,請注明出處!
感謝閱讀!