c# - 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列。我插入了一些图片以便于理解
我已经尝试了几个小时的多个代码并不断出错。以下是我的代码以及遇到的错误:
错误:无法在空引用的运行时绑定中执行
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();
}
}
}
}
我将不胜感激任何帮助。谢谢!!
解决方案
试试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 条件运算符。
推荐阅读
- python-3.x - 从雅虎财经的字符串中解析日期时间
- javascript - 如何解决茉莉花错误“加载时出错:脚本错误。” 什么时候使用jquery?
- javascript - 如何使用函数在反应中插入重复
- wordpress - 精选图片未出现
- reactjs - 每当 React Formik 发生错误时更改现有输入字段的样式
- r - 在 MacOS 上从 R 运行 psql : sh: psql: command not found
- javascript - Javascript:更新矩阵中的列
- node.js - 无服务器离线开始工作,但部署时出现内部服务器错误
- typescript - 如何在打字稿中键入部分应用的函数?
- jenkins - 将某些工件从 Artifactory(JFrog) 拉入我的 Rundeck 服务器