How to read excel file from SharePoint Site by python code via Graph API?

Vinod Survase 4,741 Reputation points
2024-01-25T08:01:13.9933333+00:00

How to read excel file from SharePoint Site by python code via Graph API?

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
12,041 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Azizkhon Ishankhonov 435 Reputation points
    2024-01-26T13:38:21.2633333+00:00

    Hi You may retrieve files from SharePoint in two different ways.

    1. Through the site, provide the site ID and then get the list of items in the root https://graph.microsoft.com/v1.0/sites/{site-id}/drive/root/children
    2. Sharepoint files are also stored in the drive. So you can access them by drive.
      For example, the curl below will return the file as a stream
      https://graph.microsoft.com/v1.0/drives/{drive-id}/items/{driveItem-id}/content

    User's image

    User's image

    Example in Python via Graph SDK

    import asyncio from azure.identity import DeviceCodeCredential
    from msgraph import GraphServiceClient 
    credential = DeviceCodeCredential(
        tenant_id='tenant id',
        client_id='client id',
        client_secret='client secret'
      )
    scopes= ['https://graph.microsoft.com/.default']
    client = GraphServiceClient(credentials=credential, scopes=scopes)
    async def get_drive_item():
        item = await client.drives.by_drive_id('drive id').items.by_drive_item_id('item id').content.get()
        if item:
            with open("my_file.xlsx", "wb") as binary_file: 
            # Write bytes to file
                binary_file.write(item)              
    asyncio.run(get_drive_item())  
    
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.