1

I am trying to download an excel file from Sharepoint with the office365 module. Here's my code.

   from office365.runtime.auth.authentication_context import AuthenticationContext
   from office365.sharepoint.client_context import ClientContext
   from office365.sharepoint.file import File
   app_settings = {
     'url': 'https://xxxxx/sites/DownloadFiles',
     'client_id': 'xxxxxx',
     'client_secret': 'xxxxxx',
   }
   if name == 'main':
      ctx_auth = AuthenticationContext(url=app_settings['url'])
      ctx_auth.acquire_token_for_app(client_id=app_settings['client_id'], 
      client_secret=app_settings['client_secret'])
      ctx = ClientContext(app_settings['url'], ctx_auth)

      path = "F:\myexcel.xlsx"
      response = File.open_binary(ctx, "/Shared%20Documents/myexcel.xlsx")
      response.raise_for_status()
      with open(path, "wb") as local_file:
           local_file.write(response.content)

When I run that code, I get the following error:

400 Client Error: Bad Request for url: https://xxx/DownloadFiles/_api/web/getfilebyserverrelativeurl('/Shared%20Documents/myexcel.xlsx')/%5C$value

1 Answer 1

1

I am able to reproduce the same issue on my SPO. enter image description here

Please modify the code as below to fix it:

response = File.open_binary(ctx, "/sites/{abc}/Shared%20Documents/source.txt")

Such as i want to download file from a site collection like "https://xxxx.sharepoint.com/sites/abc", the serverrelativeurl is "/sites/abc"

You can get the serverrelativeurl via '_spPageContextInfo' object:

enter image description here

And there is another SharePoint library 'shareplum' that provided some easy ways to operate files, you may have a try.

Best Regards, Baker Kong

Sign up to request clarification or add additional context in comments.

1 Comment

CAn you explain where the {abc} exactly comes from?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.