2011-10-11 12 views
16

Sto cercando di estrarre a livello di codice da un foglio di lavoro Excel e inserirlo in una tabella di database.C# - Come faccio a ripetere tutte le righe in Excel._Worksheet?

Come determinare il numero di colonne e righe in un foglio di lavoro o altrimenti iterare le righe?

ho

Excel._Worksheet worksheet = (Excel._Worksheet)workbook.ActiveSheet; 

ho provato worksheet.Range.Rows.Count

che lancia fino

proprietà indicizzata 'Microsoft.Office.Interop.Excel._Worksheet.Range' ha argomenti non opzionali che deve essere fornito

Cosa deve essere fatto?

+0

Con quale versione di Excel stai lavorando? – JohnFx

risposta

15

Suppongo che stiate davvero cercando l'ultima riga usata. In questo caso è necessario scrivere in questo modo:

Range UsedRange = worksheet.UsedRange; 
int lastUsedRow = UsedRange.Row + UsedRange.Rows.Count - 1; 
+0

Questo è un migliore di quello che avevo in mente. –

1

Dai un'occhiata alla proprietà UsedRange in Excel.

+0

Nella Finestra Immediata, restituisce 'Eccezione da HRESULT: 0x800401A8'. codice di errore -2147221080. InnerException = null –

+0

Per qualsiasi motivo, non è possibile utilizzare la finestra Immediata di Visual Studio. Funziona bene nel codice. Nessun grosso problema, non importa di immediato. –

28
public void IterateRows(Excel.worksheet worksheet) 
{ 
    //Get the used Range 
    Excel.Range usedRange = worksheet.UsedRange; 

    //Iterate the rows in the used range 
    foreach(Excel.Range row in usedRange.Rows) 
    { 
     //Do something with the row. 

     //Ex. Iterate through the row's data and put in a string array 
     String[] rowData = new String[row.Columns.Count]; 
     for(int i = 0; i < row.Columns.Count; i++) 
      rowData[i] = row.Cells[1, i + 1].Value2.ToString(); 
    } 
} 

Questo compila e funziona semplicemente fantastico per me! Lo sto usando per estrarre le righe con campi mancanti in un log degli errori.

+0

Dovrebbe essere String [] rowData = new String [row.Columns.Count]; – eomeroff

+0

La riga foreach deve essere foreach (riga Excel.Range in usedRange.Rows)? –

+0

Effettivamente dovrebbe! – nicholeous

Problemi correlati