如何跳过某个范围内的空白列?
我使用 C# 和 Interop.Excel.Range 返回工作表的使用的列范围,并将使用的列和行写入数据网格视图。某些列返回空白/空。
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;
在写入包含数据的列时,是否有办法跳过或忽略任何空白列?
感谢您的帮助!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
关键是使用 VBA 工作表函数
CountA
,该函数返回一个值,指示给定范围内有多少个单元格有数据。基于此,您可以决定是否在DataTable
中创建列。由于表列和 Excel 范围列现在不同步,因此您需要使用在代码中设置的列名称作为相应 Excel 范围列的索引。
因此,重新调整代码可以得到:
The key to this is to use the VBA worksheet function
CountA
which 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: