我签出了answer for the question "how to detect merged cells in c# using MS interop excel",它确实确定范围是否包含合并的单元格。但是,我想确定范围是否包含一个合并的单元格。这是我的excel工作表的样子(顶部和左侧的字母分别是列号和行号):
1 2 3 4 5
+-------+-------+---+
1 | Apple | Orange| G |
+---+---+-------+---+
2 | 1 | 2 | 3 | 4 | 5 |
+---+---+---+---+---+
如您所见,有两个合并的行彼此相邻。结果,mergeCells将为true:
bool mergeCells = xlWorksheet.Range[xlWorksheet.Cells[/*row*/1, /*column*/1], xlWorksheet.Cells[/*row*/1, /*column*/3]].MergeCells;
但是,如果我像这样格式化excel单元格,则mergeCells将为false:
1 2 3 4 5
+-------+---+-------+
1 | Apple | G | Orange|
+---+---+---+-------+
2 | 1 | 2 | 3 | 4 | 5 |
+---+---+---+---+---+
这是我项目中的所有代码。它抓住了每个顶部单元格的宽度:
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++;
}