C# Interop Excel: Checking if a range contains only one merge cell

227 Views Asked by At

I checked out the answer for the question "how to detect merged cells in c# using MS interop excel" and it does identify if a range contains merged cells. However, I want to determine if a range contains one merged cell. Here's what my excel sheet looks like (The letters at the top and left side are the column and row numbers respectively):

    1   2   3   4   5
  +-------+-------+---+
1 | Apple | Orange| G |
  +---+---+-------+---+
2 | 1 | 2 | 3 | 4 | 5 |
  +---+---+---+---+---+

As you can see, there's two merged rows right next to each other. As a result,mergeCells will be true:

bool mergeCells = xlWorksheet.Range[xlWorksheet.Cells[/*row*/1, /*column*/1], xlWorksheet.Cells[/*row*/1, /*column*/3]].MergeCells;

However, if I format the excel cells like so, mergeCells will be false:

    1   2   3   4   5
  +-------+---+-------+
1 | Apple | G | Orange|
  +---+---+---+-------+
2 | 1 | 2 | 3 | 4 | 5 |
  +---+---+---+---+---+

Here's all the code from my project. It grabs the widths of each top cell:

    List<int> ColumbWidth = new List<int>();

    int i = 0;
    int row = 1;
    int ColLeft = 1;
    int ColRight = 1;

    while (xlWorksheet.Cells[row, ColRight].Value2 != null)
    {
        object mergeCells = xlWorksheet.Range[xlWorksheet.Cells[row, ColLeft], xlWorksheet.Cells[row, ColRight]].MergeCells;

        if (ColumbWidth.Count != 0 && mergeCells != DBNull.Value && (bool)mergeCells) //still reading merged column
        {
            ColumbWidth[i]++;
        }
        else
        {
            ColumbWidth.Add(1);

            if (ColumbWidth.Count != 1)
            {
                i++;
                ColLeft = ColRight;
            }
        }

        ColRight++;
    }
0

There are 0 best solutions below