本简短教程介绍了如何使用 C# 合并 Word 中的单元格。它包含设置 IDE 的详细信息、步骤列表、用于合并单元格的预定义函数,以及一个示例代码,该示例代码展示了如何使用 C# 合并 Word 中的表格。无需任何其他第三方工具即可完成此任务。
使用 C# 合并 Word 表格中的单元格的步骤
- 将 IDE 设置为使用 Aspose.Words for .NET 合并表格中的单元格
- 声明一个预定义方法 MergeCells 供您在应用程序中使用
- 将源 Word 文件加载到包含一个或多个表格的 Document 对象中
- 访问已加载的 Word 文件中的表格以进行合并单元格
- 访问目标合并范围的起始 cell
- 访问合并范围的结束单元格
- 通过提供起始和结束单元格来调用 MergeCells() 方法并保存文档
这些步骤有助于如何使用 C# 合并 Word 中的单元格。在您的项目中添加预定义方法,并通过提供要合并的起始和结束单元格来调用它。它将更改源文件,因此,您可以使用合并单元格的不同名称保存已加载的 Word 文件。
使用 C# 在 Word 中合并单元格的代码
using System; | |
using System.Drawing; | |
using Aspose.Words; | |
using Aspose.Words.Tables; | |
class Program | |
{ | |
static void MergeCells(Cell startCell, Cell endCell) | |
{ | |
Table parentTable = startCell.ParentRow.ParentTable; | |
// Find the start and end cell | |
Point startingCell = new Point(startCell.ParentRow.IndexOf(startCell), parentTable.IndexOf(startCell.ParentRow)); | |
Point endingCell = new Point(endCell.ParentRow.IndexOf(endCell), parentTable.IndexOf(endCell.ParentRow)); | |
// Create a range of cells | |
Rectangle mergeRange = new Rectangle(Math.Min(startingCell.X, endingCell.X),Math.Min(startingCell.Y, endingCell.Y), | |
Math.Abs(endingCell.X - startingCell.X) + 1, Math.Abs(endingCell.Y - startingCell.Y) + 1); | |
foreach (Row currentRow in parentTable.Rows) | |
{ | |
foreach (Cell currentCell in currentRow.Cells) | |
{ | |
Point currentPos = new Point(currentRow.IndexOf(currentCell), parentTable.IndexOf(currentRow)); | |
// Check if the current cell is inside the range | |
if (mergeRange.Contains(currentPos)) | |
{ | |
currentCell.CellFormat.HorizontalMerge = currentPos.X == mergeRange.X ? CellMerge.First : CellMerge.Previous; | |
currentCell.CellFormat.VerticalMerge = currentPos.Y == mergeRange.Y ? CellMerge.First : CellMerge.Previous; | |
} | |
} | |
} | |
} | |
static void Main(string[] args) | |
{ | |
License lic = new License(); | |
lic.SetLicense("license.lic"); | |
Document doc = new Document("Table.docx"); | |
Table table = doc.FirstSection.Body.Tables[0]; | |
// Define starting and ending cells | |
Cell cellStartRange = table.Rows[0].Cells[0]; | |
Cell cellEndRange = table.Rows[1].Cells[1]; | |
// Merge all the cells | |
MergeCells(cellStartRange, cellEndRange); | |
doc.Save("Output.docx"); | |
} | |
} |
此代码演示了如何使用 C# 在 Word 中合并表格。我们添加了预定义方法 MergeCells 及其定义,然后在需要时在我们的应用程序中调用它。您可以选择部分、该部分中的表格列表,并使用其索引访问目标表以选择要合并的起始和结束单元格。您可以重复此过程以合并所需数量的单元格。
我们已经学习了如何使用 C# 合并 Microsoft Word 中的单元格。如果您想合并完整的 Word 文档,请参阅 如何使用 C# 合并 Word 文档 上的文章。