I’m using C# and Interop.Excel.Range to return a the used range of columns for a worksheet and write the used columns and rows to a datagrid view. Some of the columns are returning blank/null.
Microsoft.Office.Interop.Excel.Range excelRange = wWorksheet.UsedRange;
TabPage wTabPage = new TabPage(wWorksheet.Name.ToString());
DataGridView wDGV = new DataGridView();
wDGV.Dock = DockStyle.Fill;
wTabPage.Controls.Add(wDGV);
Sheets_TabControl.TabPages.Add(wTabPage);
DataTable dt = new DataTable();
DataRow wNewRow = null;
for (int i = 0; i < excelRange.Columns.Count; i++)
{
dt.Columns.Add(new DataColumn(i.ToString(), typeof(string)));
}
string wValue = string.Empty;
Microsoft.Office.Interop.Excel.Range wRange = null;
for (int wRowIndex = 1; wRowIndex <= skipRows; wRowIndex++)
{
wNewRow = dt.NewRow();
foreach (DataColumn wColumn in dt.Columns)
{
wRange = excelRange.Cells[wRowIndex, wColumn.Ordinal + 1];
if (wRange != null)
{
if (wRange.Value2 != null)
{
wValue = wRange.Value2.ToString();
if (!string.IsNullOrEmpty(wValue))
{
wNewRow.SetField(wColumn, wValue);
}
}
}
}
dt.Rows.Add(wNewRow)
}
wDGV.DataSource = dt;
Is there a way to skip or ignore any columns that are blank, while writing those columns that contain data?
Thanks for the help!
The key to this is to use the VBA worksheet function
CountAwhich returns a value indicating how many cells in a given range have data. Based on this you can decide whether or not to create a column in yourDataTable.Since your table columns and Excel range columns are now out of sync, you’ll need to use the column name you set in your code as the index of the corresponding Excel range column.
So, rejigging your code gives: