2013-07-02 45 views
0

我有一個問題。有沒有一種方法可以使用for循環遍歷電子表格中的所有列/行?現在我在我的代碼中使用這樣的foreach循環:(你可以忽略裏面發生了什麼)。GemBox - For循環行和列?

foreach (ExcelRow row in w1.Rows) 
{ 
    foreach (ExcelCell cell in row.AllocatedCells) 
    { 

     Console.Write("row: {0}", globalVar.iRowActual); 
     if (globalVar.iRowActual > 1) 
     { 
      cellValue = SafeCellValue(cell); 
      Console.WriteLine("value is: {0}", cellValue); 
     } 


    } 
    globalVar.iRowActual++; 
} 

問題是我想將每個單元格的值分配給一個新變量並將其傳遞給另一個方法。我想使用for循環爲此,我知道我可以使用CalculateMaxUsedColumns作爲cols的限制,但是有那樣的屬性,我可以用於行?!

這是我想怎樣做:

int columnCount = ws.CalculateMaxUsedColumns(); 
int rowCount = ws.CalculateMaxUsedRows(); ------> PART I NEED HELP WITH 
for(int i=0; i <columnCount; i++){ 
    for(int j = 0; j<rowCount; j++){ 
      ..... 
    } 
} 

任何形式的幫助將不勝感激。謝謝!!!

+0

我正在使用Gembox軟件來處理電子表格。 – jansyb04

回答

2

這裏有一種方法,您可以使用for循環通過電子表格中的所有列/行在GemBox.Spreadsheet中進行交互。 通過CellRange互動,由GetUsedCellRange方法返回。

CellRange range = excelFile.Worksheets.ActiveWorksheet.GetUsedCellRange(true); 

for (int i = range.FirstColumnIndex; i <= range.LastColumnIndex; i++) 
{ 
    for (int j = range.FirstRowIndex; j <= range.LastRowIndex; j++) 
    { 
     ExcelCell cell = range[j - range.FirstRowIndex, i - range.FirstColumnIndex]; 

     string cellName = CellRange.RowColumnToPosition(j, i); 
     string cellRow = ExcelRowCollection.RowIndexToName(j); 
     string cellColumn = ExcelColumnCollection.ColumnIndexToName(i); 

     Console.WriteLine(string.Format("Cell name: {1}{0}Cell row: {2}{0}Cell column: {3}{0}Cell value: {4}{0}", 
         Environment.NewLine, cellName, cellRow, cellColumn, (cell.Value) ?? "Empty")); 
    } 
}