How to count rows on a worksheet in OpenXML

I switched from the 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 sheet. I used this information to make progress. In OpenXML, I don't know how to get the same sheet information. Now I have 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++; } } 
+6
source share
1 answer

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 using LINQ right now.

+8
source

Source: https://habr.com/ru/post/983415/


All Articles