I am trying to read an Excel sheet that has some merged cells using C#. I read in another post that merged cells still existed from the code’s point of view but they just had null values. So I have tried skipping null values but I am still getting wonky results. Here is the code I am using. It is supposed to populate an HTML table with values from the spreadsheet:
private void Output_Excel_File()
{
string inputFileLocation = AppDomain.CurrentDomain.BaseDirectory + "/dashboard.xls";
DataSet ds = Get_Spreadsheet_Data(inputFileLocation, "Dashboard Statistics");
if (ds.Tables.Count > 0)
{
foreach (DataTable dt in ds.Tables)
{
int row = 0;
foreach (DataRow dr in dt.Rows)
{
int col = 0;
foreach (DataColumn dc in dt.Columns)
{
string cellValue = dr[dc].ToString();
cellValue = Regex.Replace(cellValue, "\n", "<br /");
if (cellValue == "X" || cellValue == null)
{
col++;
continue;
}
string index = "r" + row.ToString() + "c" + col.ToString();
Literal cellTarget = (Literal)form1.FindControl(index);
cellTarget.Text = cellValue;
col++;
}
row++;
}
}
}
}
In particular my indexing is off and the line:
cellTarget.Text = cellValue;
always ends up throwing a null reference exception when the indexing becomes mismatched with the indexing in the HTML.
I’ve Googled and Googled but I’m stumped. Any advice is appreciated.
From what I remember, The upper left most cell of merged cells will carry the data. Every other cell reference in the merged group will be empty.
EDIT:
If you want to skip processing r0c1 (Because I assume it doesnt exist) if it is “X” or Null, then you would have to do something like this:
Also I think cellValue will not ever be null, but it may be empty
""so I like to use:EDIT2:
You may be a bit confused with the
NullRefferenceexception that you are recieving. From what I see it not because thecellValueis null, it’s from:trying to find r0c1 which I assume doesn’t exist and returns a null control(Literal). So when you go to use
you get a NullReference error because the object itself
cellTargetis null.