Shashika
Shashika

Reputation: 1

How to upload an excel file to a sharepoint folder using Python

Here is the code that I have tried. But it didn't work for me. The file didn't get uploaded to the SharePoint Folder.Can anyone give me a solution for the problem.

url = 'https://companyname.sharepoint.com/sites/SiteName' 
username = 'username '
password = 'password'

ctx_auth = AuthenticationContext(url)
ctx_auth.acquire_token_for_user(username, password)   
ctx = ClientContext(url, ctx_auth)

path = "./book1.xlsx" #local path 
with open(path, 'rb') as content_file:
    file_content = content_file.read()
    target_url = "/sites/SiteName/SharedDocuments/book1.xlsx"  # target url of a file 
    print target_url
    File.save_binary(ctx, target_url, file_content)

Upvotes: 0

Views: 570

Answers (1)

Baker_Kong
Baker_Kong

Reputation: 1889

Is your documnet library 'SharedDocuments' or 'Shared Documents'?

You may also take a reference below code:

from office365.runtime.auth.authentication_context import 

AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.file_creation_information import FileCreationInformation
import os

tenant_url= "https://xxx.sharepoint.com"
site_url="https://xxx.sharepoint.com/sites/testprivate"

ctx_auth = AuthenticationContext(tenant_url)
ctx_auth.acquire_token_for_user("[email protected]","pass")     

ctx = ClientContext(site_url, ctx_auth)

path = r"D:\dest.txt"

with open(path, 'rb') as content_file:
    file_content = content_file.read()

list_title = "Documents"
target_folder = ctx.web.lists.get_by_title(list_title).rootFolder

info = FileCreationInformation()
info.content = file_content
info.url = os.path.basename(path)
info.overwrite = True

target_file = target_folder.files.add(info)
ctx.execute_query()

print(target_file)

BR

Upvotes: 0

Related Questions