2015-03-06 16 views
6

Sono passato dalla libreria Interop allo OpenXML, perché ho bisogno di leggere i file grandi Excel. Prima che potessi usare:Come contare le righe per foglio di lavoro in OpenXML

worksheet.UsedRange.Rows.Count 

per ottenere il numero di righe con dati sul foglio di lavoro. Ho usato queste informazioni per fare una barra di progressione. In OpenXML non so come ottenere le stesse informazioni sul foglio di lavoro. Quello che ho ora è questo codice:

using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(path, false)) 
{ 
    WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart; 
    WorksheetPart worksheetPart = workbookPart.WorksheetParts.First(); 
    SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First(); 
    int row_count = 0, col_count; 
    // here I would like to get the info about the number of rows 
    foreach (Row r in sheetData.Elements<Row>()) 
    { 
     col_count = 0; 
     if (row_count > 10) 
     { 
      foreach (Cell c in r.Elements<Cell>()) 
      { 
       // do some stuff 
       // update progressbar 
      } 
     } 
     row_count++; 
    } 
} 

risposta

8

Non è così difficile (Quando si utilizza LINQ),

using (SpreadsheetDocument myDoc = SpreadsheetDocument.Open("PATH", true)) 
{ 
    //Get workbookpart 
    WorkbookPart workbookPart = myDoc.WorkbookPart; 

    //then access to the worksheet part 
    IEnumerable<WorksheetPart> worksheetPart = workbookPart.WorksheetParts; 

    foreach (WorksheetPart WSP in worksheetPart) 
    { 
     //find sheet data 
     IEnumerable<SheetData> sheetData = WSP.Worksheet.Elements<SheetData>();  
     // Iterate through every sheet inside Excel sheet 
     foreach (SheetData SD in sheetData) 
     { 
      IEnumerable<Row> row = SD.Elements<Row>(); // Get the row IEnumerator 
      Console.WriteLine(row.Count()); // Will give you the count of rows 
     } 
} 

cura con Linq ora è il dritto in avanti.

+0

Quindi, ho dovuto fare questo ciclo in anticipo? Solo per contare le righe? Lo chiedo, perché nel ciclo principale in cui elaboro i dati aggiorno progressbar, ma prima dovevo impostare la sua proprietà Maximum (che è il numero di righe sul foglio di lavoro) – Jacobian

+0

Scusate postate in fretta ... prova il newsest update :) Utilizza LINQ –

+0

Per la tua risposta .. no non ti servirà :) La mia risposta fornisce il numero di righe disponibili per tutti i fogli in foglio di lavoro .. utilizza semplicemente il codice fornito :) –

Problemi correlati