首页 > 解决方案 > Winforms:迭代同一列的excel行时出错

问题描述

为有些令人困惑的解释道歉。我正在使用 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列。我插入了一些图片以便于理解DTG

我已经尝试了几个小时的多个代码并不断出错。以下是我的代码以及遇到的错误:

错误:无法在空引用的运行时绑定中执行

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();
                    }
                }
            }
        }

我将不胜感激任何帮助。谢谢!!

标签: c#excel

解决方案


试试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 条件运算符。


推荐阅读