如何使用Python将Excel文件上传到Sharepoint文件夹

时间:2019-12-05 10:53:02

标签: python-2.7 sharepoint

这是我尝试过的代码。但这对我没有用。该文件未上传到SharePoint文件夹。有人可以给我解决该问题的方法。

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)

1 个答案:

答案 0 :(得分:1)

您的documnet库是“ SharedDocuments”还是“ Shared Documents”?

您也可以在下面的代码中进行引用:

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("abc@xxx.onmicrosoft.com","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