如何检查单元格是否为空(Excel \ VisualC#)

这对你来说可能是一个简单的问题,我看到很多关于它的话题,但是没有一个给我提供我需要的答案。 我的目标是检查Sheet1中每行的行数,以便发现有多less行,所以我把一个do \,而它应该停止,一旦它到达一个空白的单元格

例:

row1数据
row2数据
row3数据
row4数据
row5数据

row6数据
row7数据

在这种情况下,我只需要前5行,所以do \ while检查一旦到达空白单元就会停止。 这不会发生,因为检查不会循环(即使填充了数据,它会在find空白单元格的圆圈之后停止)。

 string str; int rCnt = 11; //the data I need is after the 10th row in excel int cCnt = 1; int valori = 1; Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(label4.Text, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false); Excel.Sheets xlsheet = xlWorkbook.Worksheets; string sheet1 = "Sheet1"; Excel.Worksheet xlWorksheet = (Excel.Worksheet)xlsheet.get_Item(sheet1); Excel.Range xlCell; do { rCnt++; str = "A" + rCnt; xlCell = (Excel.Range)xlWorksheet.get_Range(str, str); } while (xlCell.Value2 == null); 

我试着将Value2更改为ValueText并尝试设置==“”而不是null。

如果你想循环到达空白单元时停止然后..试着改变

 while (xlCell.Value2 == null); 

 while (! IsNull(xlCell.Value2)); 

这个问题主要来自当你不知道什么样的数据期望。 当我使用Excel阅读时,我经常做类似于以下的事情:

 var _cell = range.Cells[1, 2].Value2; if (_cell.GetType() != typeof(Double)) 

在你的实例中,如果你总是得到一个string返回,那么你应该能够承担演员:

 string _str = (string)(range.Cells[str, str] as Excel.Range).Value2; 

然后检查是不是空的。

检查单元格的简单方法是空的:

  if (sheet.Cells[4,3] == null || sheet.Cells[4,3].Value2 == null || sheet.Cells[4,3].Value2.ToString() == "") MessageBox.Show(“cell on row 4 col 3 is empty”);