Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count rows per worksheet in OpenXML

Tags:

c#

openxml

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++;
    }
}
like image 794
Jacobian Avatar asked Mar 06 '15 10:03

Jacobian


1 Answers

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.

like image 64
Kavindu Dodanduwa Avatar answered Sep 28 '22 10:09

Kavindu Dodanduwa