Excel:具有多个区域的范围的值 [英] Excel: Values from Ranges With Multiple Areas

查看:291
本文介绍了Excel:具有多个区域的范围的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用C#在excel中获取非连续的多区域范围的值。我看到另一个SO问题,表示我可以这样做: / p>

I would like to get the values of a non contiguous, multi area range in excel using C#. I have seen another SO question that says I can do something like this:

obj[,] data = sheet.get_Range("B4:K4,B5:K5").get_Value();

但是,当我检查结果时,我看到我只从第一个区域获取数据: code>B4:K4。

However, when I examine the result I see that I only get the data from the first area: "B4:K4".

进一步测试,我发现如果以下列方式请求数据: / p>

Testing further, I found that if I request the data in the following way:

obj[,] data = sheet.get_Range( "B4:K4","B5:K5").get_Value();

我获取了这两个区域的数据...

I get the data for both areas...

所以,我的问题是,有没有办法以编程方式组合区域地址,例如B4:K4,B5:K5,以获得所有

So, my question is, is there a way to programmatically combine area addresses such as "B4:K4,B5:K5" in order to get all of the data to which they refer?

谢谢

推荐答案

解决方案想出来的不是像我想要的那样优雅,但是它的确是窍门:

The solution I came up with isn't as elegant as I would have liked but it does the trick nonetheless:

public List<List<object>> 
GetNonContiguousRowValue(Excel.Worksheet ws, string noncontiguous_address)
{
    var addresses = noncontiguous_address.Split(','); // e.g. "A1:D1,A4:D4"
    var row_data = new List<List<object>>();

    // Get the value of one row at a time:
    foreach (var addr in addresses)
    {
        object[,] arr = ws.get_Range(addr).Value;
        List<object> row = arr.Cast<object>)
                              .Take(arr.GetLength(dimension:1))
                              .ToList<object>();
        row_data.Add(row);
    }
    return row_data;
}

希望这有助于别人...

Hope this helps someone else...

这篇关于Excel:具有多个区域的范围的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆