如何使用C#从Excel中的非相邻单元格读取数据 [英] How to read the data from Non Adjacent Cells in Excel using C#

查看:127
本文介绍了如何使用C#从Excel中的非相邻单元格读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Excel工作表,其中我选择了多个彼此不相邻的单元格。当用户单击按钮时,我们需要读取所有单元格数据,对其进行处理并将其写入其他某个单元格。

I have an excel sheet, in which i have multiple cells selected, which are not adjacent to each other. When the user click on the button, we need to read all the cells data, process it and write it to some other cell.

如果单元格彼此相邻,我能够获取范围并能够执行操作。但是,如果单元格彼此不相邻,我将无法获得范围。
Selection.Range 总是给出我们选择的最后一个单元格的地址。

If the cells are adjacent to each other, i was able to get the range and able to perform the operation. But if the cells are not adjacent to each other, i am not able to get the range. The Selection.Range is always giving the address of the last cell we selected.

但是我们需要获取的地址所有的单元格,我都无法做到。

But we need to get the addresses of all Cells, which i am not able to do it.

请有人可以建议我处理这种情况的方法。

Please can anybody suggest me a way to handle this scenario.

示例代码:

Range objRange = (Range) Globals.ThisAddIn.Application.Selection;
                int nColCount = objRange.Columns.Count;
                int nRowCount = objRange.Rows.Count;

Vinay,

我已经尝试过代码根据您的建议

I have tried this code based on your suggestion,

 Range objRange = (Range) Globals.ThisAddIn.Application.Selection;

        foreach (Range cell in objRange)
        {
            MessageBox.Show("" + cell.Value2);
        }

但这没有用。总是会给出最后选择的单元格。我选择了A1,A4,A13,A16单元。但是此代码仅返回A16单元格值。

But it didn't worked. Always it's giving the last selected cell. i have selected A1, A4, A13, A16 cells. But this code is returning the A16 Cell Value Only.

推荐答案

尝试了很多之后,我得到了答案。

After trying alot, I got the answer.

这里是工作代码,

Areas objAreas = (Areas)objRange.Areas;
foreach (Range area in objAreas)
{
   string CellAddress = (GetExcelColumnName(area.Column) + "" + area.Row);
   MessageBox.Show(CellAddress);
}

GetExcelColumnName是您编写的用于将列号转换为列代码的自定义函数(例如a,b,... aa,ab等。)

GetExcelColumnName is the custom function u have written to convert Column number to Column Code(like a, b,... aa, ab.. etc)

这篇关于如何使用C#从Excel中的非相邻单元格读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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