Reputation: 413
As to MSDN the basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook.
For example, there is one workbook with sheets:
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheets>
<sheet name="MySheet1" sheetId="1" r:id="rId1" />
<sheet name="MySheet2" sheetId="2" r:id="rId2" />
</sheets>
</workbook>
And two worksheets such as:
<?xml version="1.0" encoding="UTF-8" ?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetData>
<row r="1">
<c r="A1">
<v>100</v>
</c>
</row>
</sheetData>
</worksheet>
My task is to get Worksheet by name of its Sheet. But I don't understand what is relationship beetwen Sheet and Worksheet. Ok, I found Sheet with expected name "MySheet2" in Sheets, but how can I get appropriate Worksheet? Worksheet class doesn't have name-attributes or some "foreign keys" to link with Sheet.
Upvotes: 6
Views: 5132
Reputation: 12815
Your answer is correct in that you need to use the relationship id but you can simplify your code a little by using the Descendants<T>
and GetPartById
methods:
//find the sheet by name
Sheet sheet = workbookPart.Workbook.Descendants<Sheet>().FirstOrDefault(
s => s.Name.ToString().Equals(sheetName, StringComparison.InvariantCultureIgnoreCase));
if (sheet != null)
{
string relationshipId = sheets.First().Id.Value;
//get the worksheetpart by Id
WorksheetPart worksheetPart = (WorksheetPart)workbookPart.GetPartById(relationshipId);
//get the sheetdata from the worksheet
SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();
}
Upvotes: 9
Reputation: 413
I'v solved it. There is relationship ID in Sheet. Simple example here:
string sheetName = "MySheet2";
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(@"path\to\file", false))
{
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
var sheets = workbookPart.Workbook.Sheets.Cast<Sheet>().ToList();
// Get and remember id of sheet with sheetName
string rId = "";
sheets.ForEach(x => { if (x.Name.Value == sheetName) rId = x.Id.Value; });
// Go through the WorksheetParts and find workbookPart with RelationshipId = rId
foreach (var w in workbookPart.WorksheetParts)
{
string partRelationshipId = workbookPart.GetIdOfPart(w);
if (partRelationshipId == rId)
{
SheetData sheetData = w.Worksheet.Elements<SheetData>().First();
foreach (Row r in sheetData.Elements<Row>())
{
foreach (Cell c in r.Elements<Cell>())
{
...
}
}
}
}
}
Upvotes: 3