Home > database >  Excel read cell is empty?
Excel read cell is empty?

Time:11-26

Hey guys my Problem is when i read the cell and in the cell is nothing i have an error how can i check that?

var aExcel = sh.Cells[26, 2].Value.ToString();
 double test = Convert.ToDouble(aExcel);

and a other question how can i read more cells ? because my code is so long ...

var aExcel = sh.Cells[26, 2].Value.ToString();
var bExcel = sh.Cells[27, 2].Value.ToString();
var cExcel = sh.Cells[28, 2].Value.ToString();
var dExcel = sh.Cells[29, 2].Value.ToString();
var eExcel = sh.Cells[30, 2].Value.ToString();
var fExcel = sh.Cells[31, 2].Value.ToString();
double test1 = Convert.ToDouble(aExcel);
double test2 = Convert.ToDouble(bExcel);
double test3 = Convert.ToDouble(cExcel);
double test4 = Convert.ToDouble(dExcel);
double test5 = Convert.ToDouble(aExcel);

CodePudding user response:

for your second question here is example code:

List<Double> datas = new List<Double>();

int excelStartRow = 26;
int excelEndRow = 21;


for (int i = excelStartRow; i <= excelEndRow; i  )
{
    var aExcel = sh.Cells[i, 2];
    if (aExcel != null)
    {
       double value = Convert.ToDouble(aExcel.Value.ToString());
        datas.Add(value);
    }

}

CodePudding user response:

You can check like this:

 if(sh.Cells[26, 2] != null)
{
//do something
}

code:

double test;
var aExcel = sh.Cells[26, 2];
if(aExcel != null){
test = Convert.ToDouble(aExcel.Value.ToString());
}
 
  • Related