5

我的目标是检查每行的行Sheet1以发现有多少行,所以我放了一个 do\while ,一旦它到达一个空白单元格就应该停止

例子:

第1行数据第2行
数据第3行
数据
第4行数据
第5行数据

第 6 行数据
第 7 行数据

在这种情况下,我只需要前 5 行,因此 do\while 检查旨在在到达空白单元格后停止。这不会发生,因为检查不会循环(它在完成一个圆圈后停止,就像它找到一个空白单元格,即使它充满了数据)。

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

我尝试更改Value2ValueorText并尝试设置 == "" 而不是 null。

4

6 回答 6

4

如果您希望循环在到达空白单元格时停止,那么..尝试更改

while (xlCell.Value2 == null);

while (! IsNull(xlCell.Value2));
于 2013-06-15T12:55:53.530 回答
2

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

 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”);
于 2017-06-27T13:16:25.777 回答
2

您可以使用Text所选单元格的属性。它可以通过“as”转换为字符串类型。在 C# 中已经可以像往常一样检查结果字符串,比如 not-empty

string TempText = excelWorksheet.Cells[1, 1].Text as string;
if (!string.IsNullOrWhiteSpace(TempText)){
// actions
}
于 2020-05-17T09:50:48.367 回答
1

问题主要来自当您不知道期望什么样的数据时。当我使用 Excel 读取时,我经常做类似的事情:

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

在你的例子中,如果你总是得到一个返回的字符串,那么你应该能够假设演员:

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

然后检查是否为空。

于 2015-01-06T13:32:34.650 回答
0

这对我有用:

用于Excel = Microsoft.Office.Interop.Excel;阅读 excelsheet:

var excelApp = new Excel.Application();
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(path, 0, false, 5, "", "", false, XlPlatform.xlWindows, "", true, false, 0, true, false, false);

Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelWorkbook.Sheets[2];

Excel.Range excelRange = excelWorksheet.UsedRange;
int rowCount = excelRange.Rows.Count;
int colCount = excelRange.Columns.Count;
string wwdEmpty = Convert.ToString(excelRange.Cells[5, 14].value2);
// this is working code with NULL Excell cell 
于 2019-07-01T04:58:21.123 回答
-1
do
{
    rCnt++;
    str = Sheet.Cells[rCnt, 5].Value;
} while (str != null);
于 2018-10-06T11:47:29.090 回答