如何使用MS Interop Excel在C#中检测合并的单元格 [英] how to detect merged cells in c# using MS interop excel

查看:91
本文介绍了如何使用MS Interop Excel在C#中检测合并的单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在行/整张纸中检测合并的单元格(最好)。这是我的代码

I want to detect merged cells either in a row/entire sheet(preferable).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;

这两段代码都不是

if (ws.Cells.MergeCells)
{

}

也不提供这段代码(仅适用于row1)

Nor this piece of code(only for row1)

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

似乎可以工作。.请让我知道如何

seem to work..Kindly let me know how to check if a sheet/specific range contains merged cells.

推荐答案

如果要检查范围是否包含合并的单元格,然后 MergeCells 属性就是您想要的。

If you want to check if a Range contains merged cells, then the MergeCells property is what you're after.

如果范围被合并,它将返回 true 。如果范围包含合并的单元格(即某些已合并,有些则未合并),它将返回 DBNull.Value

If a range is merged, it will return true. If a range contains merged cells (i.e. some are merged, some aren't), 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;

这篇关于如何使用MS Interop Excel在C#中检测合并的单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆