sad*_*ana 6 c# excel excel-interop
我想在行/整张表中检测合并的单元格(最好).这是我的代码
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;
Run Code Online (Sandbox Code Playgroud)
这段代码都没有
if (ws.Cells.MergeCells)
{
}
Run Code Online (Sandbox Code Playgroud)
也不是这段代码(仅适用于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;
}
}
Run Code Online (Sandbox Code Playgroud)
似乎工作..请告诉我如何检查工作表/特定范围是否包含合并的单元格.
如果您想检查 a 是否Range包含合并的单元格,那么该MergeCells属性就是您所追求的。
如果一个范围被合并,它将返回true。如果一个范围包含合并的单元格(即有些被合并,有些没有),它将返回DBNull.Value。
因此,这应该适用于您的整个工作表:
object mergeCells = ws.UsedRange.MergeCells;
var containsMergedCells = mergeCells == DBNull.Value || (bool)mergeCells;
Run Code Online (Sandbox Code Playgroud)
小智 6
MergeCells 不是单元格函数,它是范围函数,所以不是:
if (ws.Cells[strtRow, j].MergeCells)
Run Code Online (Sandbox Code Playgroud)
你需要:
_Excel.Range range = (_Excel.Range) ws.Cells[strtRow, j];
if(range.MergeCells) //returns true if cell is merged or false if its not
Run Code Online (Sandbox Code Playgroud)