工作表与工作表的关系

cha*_*_sv 3 c# excel openxml openxml-sdk

对于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>
Run Code Online (Sandbox Code Playgroud)

以及两个工作表,例如:

<?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>
Run Code Online (Sandbox Code Playgroud)

我的任务是按工作表的名称获取工作表。但我不明白甜菜表和工作表是什么关系。好的,我在 Sheets 中找到了具有预期名称“MySheet2”的 Sheet,但是我怎样才能获得合适的 Worksheet?Worksheet 类没有名称属性或一些“外键”与 Sheet 链接。

pet*_*ids 5

您的答案是正确的,因为您需要使用关系 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();
}
Run Code Online (Sandbox Code Playgroud)