Mesclar células no Word usando C#

Este breve tutorial descreve como mesclar células em Word usando C#. Ele tem os detalhes para definir o IDE, uma lista de etapas, uma função predefinida para combinar as células e um código de exemplo mostrando como mesclar tabelas no Word usando C# com a ajuda desta função predefinida. Não há necessidade de nenhuma outra ferramenta de terceiros para realizar esta tarefa.

Etapas para mesclar células em uma tabela do Word usando C#

  1. Defina o IDE para usar Aspose.Words for .NET para combinar células em uma tabela
  2. Declare um método predefinido MergeCells para uso em seu aplicativo
  3. Carregue o arquivo Word de origem no objeto Document que contém uma ou mais tabelas
  4. Acesse a tabela no arquivo Word carregado para mesclar células
  5. Acesse o cell inicial do intervalo de mesclagem de destino
  6. Acesse a célula final do intervalo de mesclagem
  7. Chame o método MergeCells() fornecendo as células iniciais e finais e salve o documento

Essas etapas ajudam em como mesclar células no Word usando C#. Adicione o método predefinido em seu projeto e chame-o fornecendo a célula inicial e final que você deseja mesclar. Isso mudará o arquivo de origem, portanto, você pode salvar o arquivo Word carregado com um nome diferente com as células mescladas.

Código para combinar células no Word usando C#

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");
}
}

Este código demonstra como combinar tabelas no Word usando C#. Adicionamos um método predefinido MergeCells junto com sua definição e então o chamamos em nosso aplicativo sempre que necessário. Você pode selecionar a seção, uma lista de tabelas naquela seção e acessar a tabela de destino usando seu índice para escolher as células iniciais e finais para mesclagem. Você pode repetir esse processo para mesclar células quantas forem necessárias.

Aprendemos como mesclar células no Microsoft Word usando C#. Se você quiser mesclar documentos completos do Word, consulte o artigo em Como mesclar documentos do Word usando C#.

 Português