【发布时间】:2019-01-15 11:00:10
【问题描述】:
对于有些令人困惑的解释,我们深表歉意。我正在使用 Microsoft.Office.Interop.Excel。下面代码的目的是为了
1) 遍历名为 oSheet1 的 Excel 工作表的 B 列中的所有行
2) 迭代datagridview (DTG) Column 0中的所有行
3) 如果 B 列和 0 列的数据匹配,则将 DTG 的 1 列中的数据导出到 excel 的 C 列。
因此,DTG 第 1 列中的数据与 DTG 中第 0 列中的数据是参考的。并且excel C列中的数据最终将参考excel B列。为了便于理解,我插入了一些图片
我已经尝试了几个小时的多个代码并不断出错。以下是我的代码以及遇到的错误:
错误:无法在空引用上执行运行时绑定
for (int i = 1; i <= oSheet1.Columns.Count; i++)
{
string cellvalue = oSheet1.Cells[i, 2].Value.ToString(); //error here
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if ((string)row.Cells[0].Value == cellvalue)
{
for (int j = 0; j < dataGridView1.Rows.Count; j++)
{
oSheet1.Cells[i, 3] = dataGridView1.Rows[j].Cells[1].Value.ToString();
}
}
}
错误:H 结果异常
for (int i = 1; i <= oSheet1.Columns.Count; i++)
{
object cellvalue = oSheet1.get_Range("B:B" + Convert.ToString(i));
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[0].Value == cellvalue)
{
for (int j = 0; j < dataGridView1.Rows.Count; j++)
{
oSheet1.Cells[i, 3] = dataGridView1.Rows[j].Cells[1].Value.ToString();
}
}
}
}
如果有任何帮助,我将不胜感激。谢谢!!
【问题讨论】:
-
您是否有意通过在
1处启动for循环来跳过第一列?循环不应该是for (int i = 0; i < oSheet1.Columns.Count; i++)吗? -
你的评论说
//error here是什么时候i是什么值? -
你在那个循环中这样做
oSheet1.Cells[i, 2](oSheet1.Cells[ROW, COL]):for (int i = 1; i <= oSheet1.Columns.Count; i++)。i用作行迭代器,但您将其与列数进行比较。 -
大家好,我明白你们的意思。是的,我做出了改变。感谢那。但错误仍然存在于同一行。