对于MSDN,SpreadsheetML文档的基本文档结构由Sheets和Sheet元素组成,它们引用了工作簿中的工作表。
例如,有一个工作簿包含工作表:
<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">
<c r="A1">
<v>100</v>
</c>
</row>
</sheetData>
</worksheet>
我的任务是按工作表的名称获取工作表。 但我不明白beetwen Sheet和Worksheet是什么关系。 好的,我在Sheets中找到了预期名称为“MySheet2”的Sheet,但是如何才能获得相应的工作表? Worksheet类没有名称属性或一些“外键”来链接Sheet。
答案 0 :(得分:2)
您的回答是正确的,因为您需要使用关系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();
}
答案 1 :(得分:0)
我解决了。 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>())
{
...
}
}
}
}
}