12

I switched from Interop library to OpenXML, because I need to read large Excel files. Before that I could use:

worksheet.UsedRange.Rows.Count

to get the number of rows with data on the worksheet. I used this information to make a progressbar. In OpenXML I do not know how to get the same information about the worksheet. What I have now is this code:

 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++;
    }
}
Jacobian
  • 9,082
  • 25
  • 109
  • 208

1 Answers1

15

It's not that hard (When you use 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
      }
}

Edited with Linq now it's straight forward.

Kavindu Dodanduwa
  • 10,909
  • 3
  • 31
  • 44