Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

excel

cell

My aim is to check line per line in the Sheet1 in order to discover how many rows are, so i put a do\while that should stop once it reaches a blank cell

Example:

row1 data
row2 data
row3 data
row4 data
row5 data

row6 data
row7 data

In this case I need only the first 5 rows, so the do\while check is intended to stop once it reaches the blank cell. This doesn't happens, because the check doesn't loop (it stops after completing a circle like it finds a blank cell even if it is filled with data).

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

I tried changing Value2 to Value or Text and trying to set == "" instead of null.

like image 348
Daniele Avatar asked Mar 24 '23 13:03

Daniele


1 Answers

If you want the loop stop when reach blank cell then .. Try to change

while (xlCell.Value2 == null);

with

while (! IsNull(xlCell.Value2));
like image 120
matzone Avatar answered Apr 06 '23 00:04

matzone