如何在 MS Word 文档中使用 C# 添加表格行

如何在 MS Word 文档中使用 C# 添加表格行

在此教程中,您将学习如何在 MS Word 文档中编程添加行,使用 C#. 您将在指定的指数中添加行,并在表端插入多个空行。

在Word文档中将线条添加到表中的好处

  • 动态内容管理:- 轻松修改现有表格以适应新数据。

  • 灵活性:- 按程序调整桌面结构,没有手动编辑。

  • 自动化:- 通过自动脚本有效地管理表数据。

原标题:准备环境

  • 安装了 Visual Studio 或任何 .NET IDE。
  • 确保 Aspose.Words 图书馆通过 NuGet 可用。

步骤指南 将字符串添加到 Word 中的表格

步骤1:安装 Aspose.Words 图书馆

使用 NuGet 包管理器安装 Aspose.Words 包。

Install-Package Aspose.Words

步骤2:进口所需的名称空间

在您的项目中包含 Aspose.Words 和 Aspose.Words.Tables 名称空间。

using Aspose.Words;
using Aspose.Words.Tables;

步骤3:打开文档

下载现有 MS Word 文档。

Document MSWordDocument = new Document(@"MS Word.docx");

步骤4:进入桌子

从文件中获取表以其指数。

Table tableToAddRowsTo = MSWordDocument.FirstSection.Body.Tables[0];

步骤5:创建或克隆一个线条

创建一个新的线路或从桌子上克隆一个现有线路。

Row row = new Row(MSWordDocument);

步骤6:将细胞添加到线上

将细胞和文本添加到字符串中。

for (int i = 0; i < 3; i++) 
{
    Cell cell = new Cell(MSWordDocument);
    cell.AppendChild(new Paragraph(MSWordDocument));
    cell.FirstParagraph.Runs.Add(new Run(MSWordDocument, "Text in Cell " + i));
    row.Cells.Add(cell);
}

步骤7:将轮子添加到结尾

使用 RowCollection. Add 将 Rows 添加到桌子上。

tableToAddRowsTo.Rows.Add(row);

步骤8:将线条插入一个特定的指数

使用 RowCollection.Insert 在一个特定的索引中插入路径。

tableToAddRowsTo.Rows.Insert(1, row);

步骤9:保存更新文件

将文件与添加行重新编辑。

MSWordDocument.Save(@"Added Rows to Table in MS Word.docx");

示例代码 将字符串添加到表中

下面是添加行到表的完整代码:

// Open MS Word Document
Document MSWordDocument = new Document(@"input.docx");

// Get the Table by index
Table tableToAddRowsTo = MSWordDocument.FirstSection.Body.Tables[0];

// Create a new Row class object
Row row = new Row(MSWordDocument);

// Add three Cells to Row's cells collection
for (int i = 0; i < 3; i++)
{
    Cell cell = new Cell(MSWordDocument);
    cell.AppendChild(new Paragraph(MSWordDocument));
    cell.FirstParagraph.Runs.Add(new Run(MSWordDocument, "Text in Cell " + i));
    row.Cells.Add(cell);
}

// Insert new Row after the first Row
tableToAddRowsTo.Rows.Insert(1, row);

// Clone an existing Row from Table
Row cloneOfRow = (Row)tableToAddRowsTo.FirstRow.Clone(true);

// Remove all content from all Cells
foreach (Cell cell in cloneOfRow)
{
    cell.RemoveAllChildren();
    cell.EnsureMinimum();
}

// Add multiple empty rows to the end of table
for (int i = 0; i < 10; i++)
{
    Row emptyRow = (Row)cloneOfRow.Clone(true);
    tableToAddRowsTo.Rows.Add(emptyRow);
}

// Save updated document
MSWordDocument.Save(@"output.docx");

结论

此教程已经展示了如何在 MS Word 文档中添加行,使用 C#. 通过遵循这些步骤,您可以有效地管理和编辑 Word 文档中的表格。

 中文