Skip to main content
 首页 » 编程设计

python之使用 Python 将 excel 文件上传到 SharePoint Online

2024年08月15日52落叶无声

我正在尝试将我的 Excel 电子表格上传到我的 SharePoint Online 网站上的文档库。 Sharepoint URL 和 SharePoint 网站上的文件夹位置列在 excel 电子表格中。

这是我现在拥有的代码:

import numpy as np 
import pandas as pd 
import xlwings as xw 
from xlwings.constants import Direction 
import sys 
import requests 
from requests_ntlm import HttpNtlmAuth 
pd.options.mode.chained_assignment = None 
 
def Upload(): 
 
    wb = xw.Book.caller() 
    ws = wb.sheets['Sheet1'] 
 
    #Read filename from excel 
    fileName = sys.argv[1] 
 
    #Enter SharePoint ONline site and target library 
    SP_URL = ws.range('C7').value 
    folder_URL = ws.range('C8').value 
 
    #Set up the url for requesting file upload 
    request_URL = SP_URL + '/_api/web/getfolderbyserverrelativeurl(\'' +  
    folder_URL + '\')/Files/asdd(url=\'' + fileName + '\',overwrite=true)' 
 
    #read in the file that we are going to upload 
    file = open(fileName, 'rb') 
 
    headers = {'Content-Type': 'application/json; odata=verbose', 'accept':  
    'application/json;odata=verbose'} 
    r = requests.post(SP_URL +  
    "/_api/contextinfo",auth=HttpNtlmAuth('Domain\\username','password'),  
    headers=headers) 
    formDigestValue = r.json()['d']['GetContextWebInformation']  
    ['FormDigestValue'] 
    headers = {'Content-Type': 'application/json; odata=verbose', 'accept':  
    'application/json;odata=verbose', 'x-requestdigest' : formDigestValue} 
    uploadResult =  
    requests.post(request_URL,auth=HttpNtlmAuth('Domain\\username','password'),  
    headers=headers, data=file.read()) 

我收到以下错误:

formDigestValue = r.json()['d']['GetContextWebInformation']['FormDigestValue']

KeyError: 'd'

请您参考如下方法:

requests_ntlm包

allows for HTTP NTLM authentication using the requests library

但是 SharePoint Online 不支持 NTLM。

而不是 requests_ntlm我建议使用 Office365-REST-Python-Client (它支持指定用户凭据并使用 SharePoint REST API)包以将文件上传到 SharePoint Online,例如:

ctx_auth = AuthenticationContext(url=settings['url']) 
if ctx_auth.acquire_token_for_user(username=settings['user_credentials']['username'], 
                                       password=settings['user_credentials']['password']): 
 
    ctx = ClientContext(settings['url'], ctx_auth) 
    target_list = ctx.web.lists.get_by_title("Documents") 
    info = FileCreationInformation() 
    file_name = "Book.xlsx" 
    path = "{0}/data/{1}".format(os.path.dirname(__file__), file_name) 
    with open(path, 'rb') as content_file: 
        info.content = content = content_file.read() 
    info.url = file_name 
    info.overwrite = True 
    upload_file = target_list.root_folder.files.add(info) 
    ctx.execute_query()