开发者

How to retrieve Open XML Relationships?

开发者 https://www.devze.com 2023-01-27 13:50 出处:网络
I\'m using the Open XML SDK 2.0 to open an Excel file. When I open the .rels file (from the .xlsx/.zip) I can see all the relati开发者_StackOverflow中文版onships defined.

I'm using the Open XML SDK 2.0 to open an Excel file.

When I open the .rels file (from the .xlsx/.zip) I can see all the relati开发者_StackOverflow中文版onships defined.

How can I get a list of these relationships in code?


SpreadsheetDocument.Parts and WorkbookPart.Parts


It depends on which relationships you want. As others have mentioned use .Parts to fetch relationship information on any OpenXmlPart.

You could do it like this:

public void GetRelationships(string filepath)
{
    using (SpreadsheetDocument spreadsheet = SpreadsheetDocument.Open(filepath, false))
    {
        // Get relationships at spreadsheet level
        IEnumerable relationships = spreadsheet.Parts;
        foreach (IdPartPair partPair in relationships)
        {
            Console.WriteLine(partPair.RelationshipId);
            Console.WriteLine(partPair.OpenXmlPart);
        }

        // Get relationships at workbook level
        IEnumerable relationships2 = spreadsheet.WorkbookPart.Parts;
        foreach (IdPartPair partPair in relationships2)
        {
            Console.WriteLine(partPair.RelationshipId);
            Console.WriteLine(partPair.OpenXmlPart);
        }

        // relationships at worksheet level
        IEnumerable worksheetParts = spreadsheet.WorkbookPart.WorksheetParts;
        foreach (WorksheetPart worksheetPart in worksheetParts)
        {
            IEnumerable relationships3 = worksheetPart.Parts;
            foreach (IdPartPair partPair in relationships3)
            {
                Console.WriteLine(partPair.RelationshipId);
                Console.WriteLine(partPair.OpenXmlPart);
            }
        }

        // Perform same concepts on any other OpenXmlPart in the package
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消