如何使用 C# 在 Word 文档中创建表格

本教程列出了使用 C# 在 Word 文档中创建表格的两种不同方法。我们将首先在 Aspose DocumentBuilder 的帮助下使用 C# 在 Word 中创建表格,然后在 Word 文档对象模型 (DOM) 中直接使用 C# 创建 Word 表格。

使用 C# 在 Word 文档中创建表格的步骤

  1. 在解决方案中引用来自 NuGet 的 Aspose.Words for .NET
  2. 导入 Aspose.Words 和 Aspose.Words.Tables 命名空间
  3. 创建 DocumentBuilderTable 类实例
  4. 使用 InsertCellTable.Rows.Cells.Add 方法在表格行中添加单元格
  5. 使用 DocumentBuilder.Write 或 Cell.AppendChild 方法插入段落文本
  6. 在表格中创建多行并在 Word 文档中完成表格创建
  7. 将表格另存为 Word 文档到磁盘上的 DOCX 格式

以下 Aspose DocumentBuilder 代码示例可在 .NET 应用程序中用于 C# Word 表创建。

使用 C# 在 Word 文档中创建表格的代码

using Aspose.Words;
using Aspose.Words.Tables;
namespace CreateTableInWordDocumentUsingCsharp
{
class CreateTableWord
{
static void Main(string[] args)
{
// Set license before C# Word table creation
License setupToCreateTable = new License();
setupToCreateTable.SetLicense(@"license file path.lic");
// Document Builder object to create Table in Word document
DocumentBuilder toCreateTableInWord = new DocumentBuilder();
// Mark the start of Word Table
Table tableInWord = toCreateTableInWord.StartTable();
// Insert a new Row & then first Cell in Word Table
toCreateTableInWord.InsertCell();
// Write text in Table Cell
toCreateTableInWord.Write("Table Row 1 and Cell 1");
// Insert a new Cell in same Word Table Row
toCreateTableInWord.InsertCell();
// Insert an Image in Word Table Cell
toCreateTableInWord.InsertImage("insert image in word table.jpg");
// Mark the end of Table Row
toCreateTableInWord.EndRow();
// Mark end of Word Table creation
toCreateTableInWord.EndTable();
// Save Word DOCX document with Table on disk
toCreateTableInWord.Document.Save("c# word table created in.docx");
}
}
}

本质上,这个创建表格 Word C# 应用程序使您能够在 Word 文档中插入表格。它首先在第一个表格行中添加两个单元格,然后在第一个单元格中写入文本内容,然后在最后一个单元格中写入 将图像添加到 Word C#

使用 C#(DOM 类)创建单词表的代码

using Aspose.Words;
using Aspose.Words.Tables;
namespace CreateWordTable
{
class CreateTableInWord
{
static void Main(string[] args)
{
// Set license before creating Word table
License license = new License();
license.SetLicense(@"license file path.lic");
Document wordDocument = new Document(); // Create empty Word document
Table wordTable = new Table(wordDocument); // Create Table object
wordTable.Rows.Add(new Row(wordDocument)); // Create a Row inside Table
wordTable.FirstRow.Cells.Add(new Cell(wordDocument)); // Create a single Cell in Table Row
wordTable.FirstRow.FirstCell.AppendChild(new Paragraph(wordDocument)); // Add a Paragraph inside Cell
// Write text content inside Word Table Cell
wordTable.FirstRow.FirstCell.FirstParagraph.Runs.Add(new Run(wordDocument, "Text in Table Row 1 and Cell 1"));
// Insert Table at the end of Word Document
wordDocument.FirstSection.Body.InsertBefore(wordTable, wordDocument.FirstSection.Body.LastParagraph);
// Save Word document to DOCX format
wordDocument.Save("c# word table created in.docx");
}
}
}

上面的 Aspose Word 创建表格 C# 代码示例只是提供了一种在 Word 文档对象模型中使用 Table、Row、Cell 和 Paragraph 类添加表格元素的替代方法。

 简体中文