I'm trying to find the dimensions of an Excel table using C# by finding the first null cell within the first column (which consists of dates) and the header row.
Here's the code I'm using right now:
public static void findingTableBounds()
{
string dateCol = "";
ArrayList dateColumn = new ArrayList();
ArrayList numberOfColumns = new ArrayList();
for (int column = 1; column < currentRow; column++)
{
dateCol = ((Excel.Range)workSheet.Cells[currentRow, 1]).Value2.ToString();
if (dateCol != "")
{
dateColumn.Add(dateCol);
currentRow++;
totalRow++;
Console.WriteLine("Total Row: {0}", totalRow);
}
else
{
Console.WriteLine("Total Row: {0}", totalRow);
currentRow = 2;
}
}
**Note: There is a closing bracket for this method, I didn't include it because there's another for loop that does the exact same thing as the above code but only for how many columns there are.
The error occurs at "dateCol = ((Excel.Range)workSheet.Cells[currentRow, 1]).Value2.ToString();" I'm pretty sure it happens because I'm trying to assign a null value (the cell) to dateCol (a string) when string is a non-nullable type. Unfortunately I'm not sure how to solve the problem.
Applying a null value to a string is doable, but if
((Excel.Range)workSheet.Cells[currentRow, 1]).Value2
is null, then it doesn't have a function ToString() is not a function, so trying to execute it doesn't work. Does it say what type of exception it is? because there might be a bigger problem...
In regards to the above post (I don't have enough reputation to comment on it)
For the sake of helping other lost souls, I upped this post and will just add:
if (((Excel.Range)workSheet.Cells[currentRow, 1]).Value2 != null) {...}.
– Sylvain Feb 16 '15 at 21:07
I had an issue and used this, but found that, in my case at least, I changed this to:
if (excelWorksheet.Cells[row, column].Value2 != null)
{
return ((Excel.Range)excelWorksheet.Cells[row, column]).Value2.ToString();
}
return "No data";
which worked for my particular case, at least. Having the Excel.Range portion in the if created errors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With