I have an Excel 2010 spreadsheet that has 3 worksheets named Sheet1, Sheet2 and Sheet3.
I'm trying to get a reference to a worksheet by name.
I'm using the code:
using (SpreadsheetDocument myWorkbook = SpreadsheetDocument.Open(FileName, true))
{
//Access the main Workbook part, which contains all references
WorkbookPart workbookPart = myWorkbook.WorkbookPart;
WorksheetPart worksheetPart = workbookPart.WorksheetParts.Last();
// this gives me Sheet1
SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
}
I am trying to get a reference to Sheet2, but I cannot find a way to do this.
I'm getting closer, but I'm not there yet:
var x = workbookPart.Workbook.Sheets.Where(s=> s.GetAttribute("name", "").Value == "Sheet2").FirstOrDefault();
That gets me a reference to the sheet, but not to the data on the sheet
Thanks
Best Answer
What you really want is the
WorksheetPart
which is what contains theSheetData
that you are looking for. Grabbing theSheets
under theWorkbook
will only give you certain metadata about the worksheets. Here is an example on how to grab thatWorksheetPart
(feel free to add error checking as you see fit as I assume thesheetName
already exists by callingFirst
and notFirstOrDefault
)Then just use your code above to grab the correct SheetData reference and you will be able to find the data you want from there.