【问题标题】:Winforms: Error in iterating excel rows of same columnWinforms:迭代同一列的excel行时出错
【发布时间】: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 &lt; oSheet1.Columns.Count; i++)吗?
  • 你的评论说//error here是什么时候i是什么值?
  • 你在那个循环中这样做oSheet1.Cells[i, 2] (oSheet1.Cells[ROW, COL]):for (int i = 1; i &lt;= oSheet1.Columns.Count; i++)i 用作行迭代器,但您将其与列数进行比较。
  • 大家好,我明白你们的意思。是的,我做出了改变。感谢那。但错误仍然存​​在于同一行。

标签: c# excel


【解决方案1】:

试试UsedRange

var range = oSheet1.UsedRange;
int startingRowIndex = range.Row + 1; //to skip the header
for (int rowIndex = startingRowIndex; rowIndex < range.Row + range.Rows.Count; rowIndex++)
{
    string cellvalue = range.Cells[rowIndex, 2].Value?.ToString();
    ...
}

此外,您应该对 Value 属性执行 null 检查,以防单元格为空,或者使用null-conditional operator,如上面的代码所示。

【讨论】:

  • 嗨,Kenny,将列更改为行。但错误仍然存​​在于同一行。至于 null 条件运算符,它使我的应用程序挂起,因此我将其删除。
  • 我会调查的。你能给我一份你的 excel 的副本(或者制作一个可以用来重现这个问题的)吗?将其发布在 GitHub 上并在此处发布链接。
  • 嗨,肯尼。附上链接(github.com/atisyam/masyita/blob/master/stackoverflow.xlsx)。感谢您的时间先生。
猜你喜欢
  • 1970-01-01
  • 2012-03-15
  • 1970-01-01
  • 2020-07-12
  • 1970-01-01
  • 1970-01-01
  • 2021-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多