如何使用Python脚本将文件上传到SharePoint网站

30 投票
7 回答
122355 浏览
提问于 2025-04-18 06:45

有没有办法用Python脚本在SharePoint网站上上传文件?我尝试安装haufe.sharepoint这个库,但在安装的时候似乎出现了问题,无法获取ntlm,而没有ntlm我就不能使用这个连接模块。

我还尝试过直接把Excel文件保存到服务器的位置(也就是把文件保存到像\server\sharepointsite\files这样的目录,而不是通过网址连接),使用openpyxl库,但看起来文件保存后仍然是被锁定状态。

如果有人能帮忙,我会非常感激。谢谢!!

7 个回答

2

上面的回答对我没用。
我找到了一种简单好用的方法,就是把我的SharePoint文件夹映射成一个驱动器,然后我就可以直接把文件复制到那个驱动器里。

import subprocess
import shutil
subprocess.call(r'net use Y: http://sharepoint/link/to/your/folder', shell=True)
shutil.copy("link_to_local_file","Y:\\")

除了复制,你还可以删除文件,或者像对待普通文件夹一样做其他操作。

3

我觉得我可能有点晚了,才来回答这个问题。

以下这个方法对我有效:

在Sharepoint网页上,找到“库工具”>>“库”>>点击“用资源管理器打开”命令(这个命令的图标在右下角,靠近“连接到Office”命令)。

地址栏会显示出我们需要上传文件的地址。记得把地址中的“http:”或“https:”去掉。这个地址就是你上传文件的目标位置。

接下来,你可以使用shutil这个包来上传文件。

import shutil as sl
sl.copy(source,destination)

这应该能帮助你把文件上传到Sharepoint。

温馨提示:这个方法在Python 3.6中效果很好。

5

你可以用SharePlum来上传文件。

首先安装SharePlum:在命令行输入 pip install SharePlum,然后试试下面的代码。

import requests
from shareplum import Office365

# Set Login Info
username = '<username>'
password = '<password>'
site_name = '<site_name>'
base_path = 'https://<domain_name>.sharepoint.com'
doc_library = 'Shared%20Documents'
nested_folder = 'Shared%20Documents/<folder1>/<folder2>' #if you want to upload in nested folders else nested_folder = doc_library
file_name = "my_file.zip" #when your file in the same directory

# Obtain auth cookie
authcookie = Office365(base_path, username=username, password=password).GetCookies()
session = requests.Session()
session.cookies = authcookie
session.headers.update({'user-agent': 'python_bite/v1'})
session.headers.update({'accept': 'application/json;odata=verbose'})

session.headers.update({'X-RequestDigest': 'FormDigestValue'})
response = session.post(url=base_path + "/sites/" + site_name + "/_api/web/GetFolderByServerRelativeUrl('" + doc_library + "')/Files/add(url='a.txt',overwrite=true)",
                         data="")
session.headers.update({'X-RequestDigest': response.headers['X-RequestDigest']})

# Upload file
with open(file_name, 'rb') as file_input:
    try:
        response = session.post(
            url=base_path + "/sites/" + site_name + f"/_api/web/GetFolderByServerRelativeUrl('" + nested_folder + "')/Files/add(url='"
            + file_name + "',overwrite=true)",

            data=file_input)
        print("response: ", response.status_code) #it returns 200
        if response.status_code == '200':
            print("File uploaded successfully")
    except Exception as err:
        print("Something went wrong: " + str(err))

print('File Uploaded Successfully')
6

haufe.sharepoint 这个工具只适用于 SharePoint 列表,但你可能需要访问文档库。

你可以使用 Python 的 Requests 库,结合 SharePoint 的 REST API 来实现你的需求。

如果你的 SharePoint 网站不支持基本认证,我建议你使用 requests_ntlm 这个包。

这个方法对我来说没有成功,可能是因为其他原因,但希望对你有所帮助。

22

我先说一下,这个例子是从Office365-REST-Python-Client的示例中改编而来的。它是用来通过REST API与Sharepoint在线互动的。

你可以在这里查看代码示例

你可能想上传文件的示例网址格式是:[基础网址][站点][文件夹][文件]。比如说:
https://your_company.sharepoint.com/path/to/site/Shared Documents/file.txt

import os
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext

baseurl = 'https://your_company.sharepoint.com'
basesite = '/path/to/site' # every share point has a home.
siteurl = baseurl + basesite 

localpath = './file.txt'
remotepath = "Shared Documents/file.txt" # existing folder path under sharepoint site.

ctx_auth = AuthenticationContext(siteurl) # should also be the siteurl
ctx_auth.acquire_token_for_user(username, password)
ctx = ClientContext(siteurl, ctx_auth) # make sure you auth to the siteurl.

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

dir, name = os.path.split(remotepath)
file = ctx.web.get_folder_by_server_relative_url(dir).upload_file(name, file_content).execute_query()

撰写回答