开发者

How to get the 'first' sheet in OOXML with C# and the SDK?

开发者 https://www.devze.com 2023-04-11 12:43 出处:网络
SO! :) Simple question -- it\'s probably been asked, but I could not find it. I am retrieving data from an XLSX using the Open XML SDK and C#.

SO! :) Simple question -- it's probably been asked, but I could not find it. I am retrieving data from an XLSX using the Open XML SDK and C#. I want to get the "first" sheet (as in the first one you would see in Excel), but when I use...

WorkbookPart wbPart = workBook.WorkbookPart;
//Now let's find the dimension of the first worksheet 
string sheetArea = wbPart.WorksheetParts.First().Worksheet.SheetD开发者_Go百科imension.Reference.Value;

Unfortunately, in a brand-new XLSX this pulled "Sheet3" instead of "Sheet1". I do not know the sheet name ahead of time nor can I force the user to submit a workbook with only one sheet or specify sheet name. My present requirements are to grab the first sheet.

Can someone please help? :)

EDIT: I figured it out! But I can't answer my own question for 7 hours, so...

I found this by digging through answers on this other SO question:

Open XML SDK 2.0 - how to update a cell in a spreadsheet?

In essence, a working example might be this :

(wbPart.GetPartById(wbPart.Workbook.Sheets.Elements<Sheet>().First().Id.Value) as WorksheetPart).Worksheet.SheetDimension.Reference.Value


As far as I know, something like:

Sheet firstSheet = wbPart.Workbook.Descendants<Sheet>().First();
Worksheet firstWorksheet = ((WorksheetPart)wbPart.GetPartById(firstSheet.Id)).Worksheet;

Should return the first worksheet. The workbook Sheet descendants should always be sorted based on the order they appear in the workbook, at least in my experience.

If you wish to get the first visible, use:

Sheet firstSheet = wbPart.Workbook.Descendants<Sheet>()
                         .First(s => s.State == SheetStateValues.Visible);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号