使用Python将excel文件上载到SharePoint Online

2024-05-15 02:40:04 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这是我现在掌握的代码:

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'


Tags: fromimportjsonurlverbosewsapplicationas
1条回答
网友
1楼 · 发布于 2024-05-15 02:40:04

requests_ntlm

allows for HTTP NTLM authentication using the requests library

SharePoint Online不支持NTLM

我建议使用^{}它支持指定用户凭据并使用SharePoint REST API)包将文件上载到SharePoint Online,而不是requests_ntlm,例如:

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()

相关问题 更多 >

    热门问题