繁体   English   中英

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

[英]How to check if a cell is empty (Excel\VisualC#)

我的目标是检查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);
    

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

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

while (xlCell.Value2 == null);

while (! IsNull(xlCell.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”);

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

string TempText = excelWorksheet.Cells[1, 1].Text as string;
if (!string.IsNullOrWhiteSpace(TempText)){
// actions
}

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

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

在您的实例中,如果您总是返回一个字符串,那么您应该能够假设演员阵容:

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

然后检查它不为空。

这对我有用:

使用Excel = Microsoft.Office.Interop.Excel; 阅读excel表:

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 
do
{
    rCnt++;
    str = Sheet.Cells[rCnt, 5].Value;
} while (str != null);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM