分享

Working with Merged Cells

 昵称17725796 2014-10-03
In a table several cells can be merged together into a single cell. This is useful when certain rows require a title or large blocks of text which span across the width of the table. This can only be achieved by merging some of the cells in the table into a single cell. Aspose.Words supports merged cells when working with all input formats including when importing HTML content.

Merged Cells in Aspose.Words

In Aspose.Words, merged cells are represented by CellFormat.HorizontalMerge and CellFormat.VerticalMerge . The CellFormat.HorizontalMerge property describes if the cell is part of a horizontal merge of cells. Likewise the CellFormat.VerticalMerge property describes if the cell is a part of a vertical merge of cells.

The values of these properties are what define the merge behavior of cells.

  • The first cell in a sequence of merged cells will have CellMerge.First.
  • Any subsequent merged cells will have CellMerge.Previous.
  • A cell which is not merged will have CellMerge.None.

Sometimes when you load an existing document cells in a table will appear merged. However these can be in fact one long cell. Microsoft Word at times is known to export merged cells in this way. This can cause confusion when attempting to work with individual cells. There appears to be no particular pattern as to when this happens.

Checking if a Cell is Merged

To check if a cell is part of a sequence of merged cells, we simply check the CellFormat.HorizontalMerge and CellFormat.VerticalMerge properties.

Example

Prints the horizontal and vertical merge type of a cell.

C#
public void CheckCellsMerged()
{
    Document doc = new Document(MyDir + "Table.MergedCells.doc");

    // Retrieve the first table in the document.
    Table table = (Table)doc.GetChild(NodeType.Table, 0, true);

    foreach (Row row in table.Rows)
    {
        foreach (Cell cell in row.Cells)
        {
            Console.WriteLine(PrintCellMergeType(cell));
        }
    }

}

public string PrintCellMergeType(Cell cell)
{
    bool isHorizontallyMerged = cell.CellFormat.HorizontalMerge != CellMerge.None;
    bool isVerticallyMerged = cell.CellFormat.VerticalMerge != CellMerge.None;
    string cellLocation = string.Format("R{0}, C{1}", cell.ParentRow.ParentTable.IndexOf(cell.ParentRow) + 1, cell.ParentRow.IndexOf(cell) + 1);

    if (isHorizontallyMerged && isVerticallyMerged)
        return string.Format("The cell at {0} is both horizontally and vertically merged", cellLocation);
    else if (isHorizontallyMerged)
        return string.Format("The cell at {0} is horizontally merged.", cellLocation);
    else if (isVerticallyMerged)
        return string.Format("The cell at {0} is vertically merged", cellLocation);
    else
        return string.Format("The cell at {0} is not merged", cellLocation);
}
 
Visual Basic
<Test> _
Public Sub CheckCellsMerged()
    Dim doc As New Document(MyDir & "Table.MergedCells.doc")

    ' Retrieve the first table in the document.
    Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

    For Each row As Row In table.Rows
        For Each cell As Cell In row.Cells
            Console.WriteLine(PrintCellMergeType(cell))
        Next cell
    Next row

End Sub

Public Function PrintCellMergeType(ByVal cell As Cell) As String
    Dim isHorizontallyMerged As Boolean = cell.CellFormat.HorizontalMerge <> CellMerge.None
    Dim isVerticallyMerged As Boolean = cell.CellFormat.VerticalMerge <> CellMerge.None
    Dim cellLocation As String = String.Format("R{0}, C{1}", cell.ParentRow.ParentTable.IndexOf(cell.ParentRow) + 1, cell.ParentRow.IndexOf(cell) + 1)

    If isHorizontallyMerged AndAlso isVerticallyMerged Then
        Return String.Format("The cell at {0} is both horizontally and vertically merged", cellLocation)
    ElseIf isHorizontallyMerged Then
        Return String.Format("The cell at {0} is horizontally merged.", cellLocation)
    ElseIf isVerticallyMerged Then
        Return String.Format("The cell at {0} is vertically merged", cellLocation)
    Else
        Return String.Format("The cell at {0} is not merged", cellLocation)
    End If
End Function
 

Merging Cells in a Table

The same technique is used to set the merge behavior on the cells in a table. When building a table with merge cells with DocumentBuilder you need to set the appropriate merge type for each cell. Also you must remember to clear the merge setting or otherwise all cells in the table will become merged. This can be done by setting the value of the appropriate merge property to CellMerge.None.

Example

Creates a table with two rows with cells in the first row horizontally merged.

C#
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.InsertCell();
builder.CellFormat.HorizontalMerge = CellMerge.First;
builder.Write("Text in merged cells.");

builder.InsertCell();
// This cell is merged to the previous and should be empty.
builder.CellFormat.HorizontalMerge = CellMerge.Previous;
builder.EndRow();

builder.InsertCell();
builder.CellFormat.HorizontalMerge = CellMerge.None;
builder.Write("Text in one cell.");

builder.InsertCell();
builder.Write("Text in another cell.");
builder.EndRow();
builder.EndTable();
 
Visual Basic
Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

builder.InsertCell()
builder.CellFormat.HorizontalMerge = CellMerge.First
builder.Write("Text in merged cells.")

builder.InsertCell()
' This cell is merged to the previous and should be empty.
builder.CellFormat.HorizontalMerge = CellMerge.Previous
builder.EndRow()

builder.InsertCell()
builder.CellFormat.HorizontalMerge = CellMerge.None
builder.Write("Text in one cell.")

builder.InsertCell()
builder.Write("Text in another cell.")
builder.EndRow()
builder.EndTable()
 
Example

Creates a table with two columns with cells merged vertically in the first column.

C#
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.InsertCell();
builder.CellFormat.VerticalMerge = CellMerge.First;
builder.Write("Text in merged cells.");

builder.InsertCell();
builder.CellFormat.VerticalMerge = CellMerge.None;
builder.Write("Text in one cell");
builder.EndRow();

builder.InsertCell();
// This cell is vertically merged to the cell above and should be empty.
builder.CellFormat.VerticalMerge = CellMerge.Previous;

builder.InsertCell();
builder.CellFormat.VerticalMerge = CellMerge.None;
builder.Write("Text in another cell");
builder.EndRow();
builder.EndTable();
 
Visual Basic
Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

builder.InsertCell()
builder.CellFormat.VerticalMerge = CellMerge.First
builder.Write("Text in merged cells.")

builder.InsertCell()
builder.CellFormat.VerticalMerge = CellMerge.None
builder.Write("Text in one cell")
builder.EndRow()

builder.InsertCell()
' This cell is vertically merged to the cell above and should be empty.
builder.CellFormat.VerticalMerge = CellMerge.Previous

builder.InsertCell()
builder.CellFormat.VerticalMerge = CellMerge.None
builder.Write("Text in another cell")
builder.EndRow()
builder.EndTable()
 

In other situations where a builder is not used, such as in an existing table, merging cells in this way may not be as simple.

Instead we can wrap the base operations which are involved in apply merge properties to cells into a method which makes the task much easier. This method is similar to the automation Merge method which is called to merge a range of cells in a table.

The code below will merge the range of cells in table starting from the given cell, to the end cell. This range can span over many rows or columns.

Example

A method which merges all cells of a table in the specified range of cells.

C#
/// <summary>
/// Merges the range of cells found between the two specified cells both horizontally and vertically. Can span over multiple rows.
/// </summary>
public static void MergeCells(Cell startCell, Cell endCell)
{
    Table parentTable = startCell.ParentRow.ParentTable;

    // Find the row and cell indices for the start and end cell.
    Point startCellPos = new Point(startCell.ParentRow.IndexOf(startCell), parentTable.IndexOf(startCell.ParentRow));
    Point endCellPos = new Point(endCell.ParentRow.IndexOf(endCell), parentTable.IndexOf(endCell.ParentRow));
    // Create the range of cells to be merged based off these indices. Inverse each index if the end cell if before the start cell. 
    Rectangle mergeRange = new Rectangle(Math.Min(startCellPos.X, endCellPos.X), Math.Min(startCellPos.Y, endCellPos.Y), 
        Math.Abs(endCellPos.X - startCellPos.X) + 1, Math.Abs(endCellPos.Y - startCellPos.Y) + 1);

    foreach (Row row in parentTable.Rows)
    {
        foreach (Cell cell in row.Cells)
        {
            Point currentPos = new Point(row.IndexOf(cell), parentTable.IndexOf(row));

            // Check if the current cell is inside our merge range then merge it.
            if (mergeRange.Contains(currentPos))
            {
                if (currentPos.X == mergeRange.X)
                    cell.CellFormat.HorizontalMerge = CellMerge.First;
                else
                    cell.CellFormat.HorizontalMerge = CellMerge.Previous;

                if (currentPos.Y == mergeRange.Y)
                    cell.CellFormat.VerticalMerge = CellMerge.First;
                else
                    cell.CellFormat.VerticalMerge = CellMerge.Previous;
            }
        }
    }
}
 
Visual Basic
''' <summary>
''' Merges the range of cells found between the two specified cells both horizontally and vertically. Can span over multiple rows.
''' </summary>
Public Shared Sub MergeCells(ByVal startCell As Cell, ByVal endCell As Cell)
    Dim parentTable As Table = startCell.ParentRow.ParentTable

    ' Find the row and cell indices for the start and end cell.
    Dim startCellPos As New Point(startCell.ParentRow.IndexOf(startCell), parentTable.IndexOf(startCell.ParentRow))
    Dim endCellPos As New Point(endCell.ParentRow.IndexOf(endCell), parentTable.IndexOf(endCell.ParentRow))
    ' Create the range of cells to be merged based off these indices. Inverse each index if the end cell if before the start cell. 
    Dim mergeRange As New Rectangle(Math.Min(startCellPos.X, endCellPos.X), Math.Min(startCellPos.Y, endCellPos.Y), Math.Abs(endCellPos.X - startCellPos.X) + 1, Math.Abs(endCellPos.Y - startCellPos.Y) + 1)

    For Each row As Row In parentTable.Rows
        For Each cell As Cell In row.Cells
            Dim currentPos As New Point(row.IndexOf(cell), parentTable.IndexOf(row))

            ' Check if the current cell is inside our merge range then merge it.
            If mergeRange.Contains(currentPos) Then
                If currentPos.X = mergeRange.X Then
                    cell.CellFormat.HorizontalMerge = CellMerge.First
                Else
                    cell.CellFormat.HorizontalMerge = CellMerge.Previous
                End If

                If currentPos.Y = mergeRange.Y Then
                    cell.CellFormat.VerticalMerge = CellMerge.First
                Else
                    cell.CellFormat.VerticalMerge = CellMerge.Previous
                End If
            End If
        Next cell
    Next row
End Sub
 
Example

Merges the range of cells between the two specified cells.

C#
// We want to merge the range of cells found inbetween these two cells.
Cell cellStartRange = table.Rows[2].Cells[2];
Cell cellEndRange = table.Rows[3].Cells[3];

// Merge all the cells between the two specified cells into one.
MergeCells(cellStartRange, cellEndRange);
 
Visual Basic
' We want to merge the range of cells found inbetween these two cells.
Dim cellStartRange As Cell = table.Rows(2).Cells(2)
Dim cellEndRange As Cell = table.Rows(3).Cells(3)

' Merge all the cells between the two specified cells into one.
MergeCells(cellStartRange, cellEndRange)
 
Depending on the version of the .NET Framework you are using, you may want to further build on this method by turning it into an extension method. In this case, you can then call this method directly on a cell to merge a range of cells e.g cell1.Merge(cell2).

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多