[英]How to get all the rows which contain data in a particular column in Excel from C#
我在Excel中有一個數據集,並且正在使用C#打開工作表並訪問一些數據。
我試圖獲取包含來自特定列的數據的所有行。 例如在B
列中,從單元格“ B3”開始向下,我想將包含數據的所有行存儲在Array之類的集合中。
這是我到目前為止的內容:
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
}
如您在上面看到的,我指定了我不想要的從B3到B45的范圍。 我想獲取B列中包含從B3開始的數據的所有行。
我將如何實現?
通常,當我陷入這些情況時,我會記錄一個宏並將VBA代碼轉換為C#。 VSTO中的對象模型幾乎完全相同(請記住,這是一個很好的技巧),並且從.Net 4.0開始,可選參數節省了大量代碼。
在您的特定情況下,我設想電子表格越大,使用VSTO讀取B列中的所有Excel單元格所需的時間就越長。 我的建議是使用此技術一次讀取所有內容:
//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.