[英]How to get all the rows which contain data in a particular column in Excel from C#
I have a data set in Excel and am using C# to open the worksheet and access some of the data. 我在Excel中有一个数据集,并且正在使用C#打开工作表并访问一些数据。
I am trying to get all the rows that contain data from a particular column. 我试图获取包含来自特定列的数据的所有行。 For example in column
B
starting from cell 'B3' going down I want to store all the rows that contain data in a collection like an Array. 例如在
B
列中,从单元格“ B3”开始向下,我想将包含数据的所有行存储在Array之类的集合中。
This is what I have so far: 这是我到目前为止的内容:
Application excelApplication;
_Workbook workbook;
_Worksheet sheet;
excelApplication = new Excel.Application
{
Visible = true,
ScreenUpdating = true
};
workbook = excelApplication.Workbooks.Open(@"C:\Documents and Settings\user\Desktop\Book1.xls");
sheet = (Worksheet)workbook.Worksheets[2];
Excel.Range range = sheet.Range["b3:b145"].
foreach (Range cell in range)
{
// Do something with rows which contain data
}
As you can see above I have specified the range from B3 to B45 which I don't want. 如您在上面看到的,我指定了我不想要的从B3到B45的范围。 I want to get all the rows in the B column which contain data starting from B3.
我想获取B列中包含从B3开始的数据的所有行。
How would I achieve this? 我将如何实现?
In general when I get stuck in these situations I record a Macro and convert the VBA code to C#. 通常,当我陷入这些情况时,我会记录一个宏并将VBA代码转换为C#。 The object model in VSTO is pretty much exactly the same (remember this its a great tip) and with .Net 4.0 onwards optional parameters save a lot of code.
VSTO中的对象模型几乎完全相同(请记住,这是一个很好的技巧),并且从.Net 4.0开始,可选参数节省了大量代码。
In your particular instance I envisage the larger the spreadsheet the longer it will take to read all the Excel cells in column B using VSTO. 在您的特定情况下,我设想电子表格越大,使用VSTO读取B列中的所有Excel单元格所需的时间就越长。 My advice is to use this technique to read them all at once:
我的建议是使用此技术一次读取所有内容:
//Work out the number of rows with data in column B:
//int lastColumn = range.Columns.Count;
int lastRow = range.Rows.Count;
//Get all the column values:
object[,] objectArray = shtName.get_Range("B3:B" + lastRow.ToString()).Value2;
rngName.Value2 = objectArray;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.