Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenXml WorksheetParts.First() is not always the 1st sheet MS Excel shows

I have XLSX files which when viewed in Excel have multiple sheets. However, some of the files using the snippet below actually have the WorksheetPart.First as the 2nd or 3rd worksheet when viewed in excel. I think this is because the sheets were re-arranged in excel at one point.

Q: How to use OpenXml to read the sheets in the "view" order that MS-Excel shows them in, versus what can be out of order via OpenXml? Note: I can't use sheet name as a workaround.

using (var document = SpreadsheetDocument.Open(".\test.xlsx", false)) { var workbookPart = document.WorkbookPart; var worksheetPart = workbookPart.WorksheetParts.First(); // worksheetPart is not always the first worksheet that Excel shows }

like image 925
Matthew Mc Avatar asked Oct 27 '25 03:10

Matthew Mc


1 Answers

I guess the worksheet parts are not necessarily in order. What should be in order though is the Workbook.Sheets property (you can also search by name here). You can correlate a Sheet with its WorksheetPart through it's Id, see here for example.

like image 192
fejesjoco Avatar answered Oct 29 '25 08:10

fejesjoco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!