工作表和工作表之间的关系

对于MSDN ,SpreadsheetML文档的基本文档结构由表单和表单元素组成,这些元素引用工作簿中的工作表。

例如,有一个带有工作表的工作簿:

<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> 

和两个工作表,如:

 <?xml version="1.0" encoding="UTF-8" ?> <worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"> <sheetData> <row r="1"> <cr="A1"> <v>100</v> </c> </row> </sheetData> </worksheet> 

我的任务是通过名单的工作表获取工作表。 但我不明白什么是关系beetwen表和工作表。 好的,我在表格中find预期名称为“MySheet2”的工作表,但是如何才能获得适当的工作表? 工作表类没有名称属性或一些“外键”与工作表链接。

您的答案是正确的,因为您需要使用关系id,但是可以使用Descendants<T>GetPartById方法简化代码:

 //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(); } 

我解决了它。 Sheet中有关系ID。 简单的例子:

  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>()) { ... } } } } }