Data validation for each cell to check whether the value is available or not using EPplus

…衆ロ難τιáo~ 提交于 2019-12-31 05:14:08

问题


I am using Epplus for uploading file.I have two sheet in .xlsx format.I want to ensure that each and every cell has value.For example in my excel i have dropdown box.If a user have details in first sheet and second sheet is empty.But this empty sheet have only one value which is added in sheet by mistake by use of this dropdown.So at this stage it will show object null reference error when it goes in to this loop

    for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
     {

         if (int.TryParse(s.Cells[rowIterator, 1].Value.ToString(), out n) && int.TryParse(s.Cells[rowIterator, 2].Value.ToString(), out n))
        {
          Pss.Pbr = Convert.ToInt32(s.Cells[rowIterator, 1].Value);
          Pss.Amount = Convert.ToInt32(s.Cells[rowIterator, 2].Value);
         Ps.Add(Pss);

        }
}

how to validate that all columns and row have values


回答1:


In the loop, check if the cell is not null and is not empty, like this:

bool allRangeHasValue=true;
for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
{
    for(int col =1;col<=s.Dimension.End.Column;col++)
    {

      if(String.IsNullOrWhiteSpace(s.Cells[rowIterator, col]?.Value?.ToString())
      {
          allRangeHasValue=false;
          break;
      }
    }
    if(!allRangeHasValue)
    {
      break;
    }
}

Edit: Based on your comment, you could do something like: Edit2: Since you're using TryParse, you don't need to parse again, TryParse returns the value in the out variable.

for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
 {
     int n1;
     int n2;
     if (!string.IsNullOrWhiteSpace(s.Cells[rowIterator, 1]?.Value?.ToString()) &&
         !string.IsNullOrWhiteSpace(s.Cells[rowIterator, 2]?.Value?.ToString()) &&
         int.TryParse(s.Cells[rowIterator, 1].Value.ToString(), out n1) && 
         int.TryParse(s.Cells[rowIterator, 2].Value.ToString(), out n2))
    {
      Pss.Pbr = n1;
      Pss.Amount = n2;
      Ps.Add(Pss);

    }
}


来源:https://stackoverflow.com/questions/44434253/data-validation-for-each-cell-to-check-whether-the-value-is-available-or-not-usi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!