How to detect merged cells in C # using MS interop excel

I want to detect merged cells either in row / whole (preferred). Here is my code

Microsoft.Office.Interop.Excel.Application xl = new Microsoft.Office.Interop.Excel.Application(); 
Microsoft.Office.Interop.Excel.Workbook workbook = xl.Workbooks.Open(source);
//Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[sheetNumber];
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[objInMemory._sheetName];
xl.ScreenUpdating = false;
ws.Columns.ClearFormats();
ws.Rows.ClearFormats();
int colCount = ws.UsedRange.Columns.Count;
int rowCount = ws.UsedRange.Rows.Count;
int strtRow = ws.UsedRange.Rows[1].Row;
int strtCol = ws.UsedRange.Columns[1].Column;


 Microsoft.Office.Interop.Excel.Range objRange = null;

      

No piece of code

if (ws.Cells.MergeCells)
{

}

      

And this piece of code (only for line1)

for (int j = strtCol; j < strtCol + colCount; j++)
{
    objRange = ws.Cells[strtRow, j];

    if (ws.Cells[strtRow, j].MergeCells)
    {
        message = "The Sheet Contains Merged Cells";
        break;
    }  
}

      

seems to work. Be sure to let me know how to check if a sheet / specific range contains merged cells.

+3


source to share


2 answers


If you want to check if it contains Range

merged cells then the property MergeCells

is what you need.

If the range is concatenated, it will return true

. If the range contains merged cells (i.e. some are merged, some are not), it will return DBNull.Value

.



So this should work for your entire sheet:

object mergeCells = ws.UsedRange.MergeCells;
var containsMergedCells = mergeCells == DBNull.Value || (bool)mergeCells;

      

+3


source


MergeCells

is not a cell function, it is a range function, so instead of:

if (ws.Cells[strtRow, j].MergeCells)

      



you need:

_Excel.Range range = (_Excel.Range) ws.Cells[strtRow, j];
if(range.MergeCells) //returns true if cell is merged or false if its not

      

+4


source







All Articles