【问题标题】:How to iterate on Excel.Range with an index in c#如何在 C# 中使用索引在 Excel.Range 上进行迭代
【发布时间】:2019-03-04 20:02:21
【问题描述】:

我正在为 excel 编写一个 c# Add in,它从 excel 工作表的列中获取值并执行一些操作。这是我写的部分代码:

        Excel.Range aqRange = currentSheet.Range["C3:C" + cRowCount];
        Excel.Range vcRange = currentSheet.Range["D3:D" + cRowCount];
        Excel.Range k0R = currentSheet.Range["F2"];
        double[] sgVett = new double[cRowCount];

        foreach (Range aq in aqRange)
        {
            if (i == 0) sgVett[i] = k0R.Value + aq.Value;
            else sgVett[i] = sgVett[i - 1] + aq.Value;
            i++;
        }
        i = 0;

        foreach (Range vc in vcRange)
        {
            if (i == 0) sgVett[i] -= vc.Value;
            else sgVett[i] -= vc.Value;
            i++;
        }

我想知道是否有办法做这样的事情:

for(int j = 0; j<cRowCount; j++) {
    if (i == 0) sgVett[i] = k0R.Value + aqRange[i].Value;
    else sgVett[i] = sgVett[i - 1] + aqRange[i].Value;
}

我知道我不能使用Excel.Range 作为向量,但是有没有办法使用索引来滚动aqRangevcRange,或者,至少,如果可以只使用一个@ 987654326@ 或一个 foreach 而不是两个(就像我做的那样)。

【问题讨论】:

    标签: c# .net excel vsto


    【解决方案1】:

    您可以使用 Range 的 Cells 属性,有点像二维数组。

    请务必注意,尽管使用的语法类似于 C# 二维数组 (Cells[RowIndex, ColIndex]),但 Cells 属性访问的 COM 对象使用 1 作为起始偏移量,而不是 0。

    所以你应该能够写出类似的东西:

    for(int j = 1; j<=cRowCount; j++)
    {
        if (i == 0) sgVett[i] = k0R.Value + aqRange.Cells[j,1].Value;
    }
    

    另见此处:Fastest way to get an Excel Range of Rows & How do I get an Excel range using row and column numbers in VSTO / C#?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-13
      • 1970-01-01
      • 2022-01-15
      • 2022-01-19
      • 1970-01-01
      • 2020-02-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多