有没有办法使用python脚本在sharepoint网站上传文件?我尝试安装haufe.sharepoint,但它似乎无法在安装时获取ntlm,而且我甚至无法在没有安装ntlm的情况下使用连接器模块。
我还尝试将excel文件保存到服务器位置(因此将其保存到目录,如\ server \ sharepointsite \ files,而不是通过URL连接)使用openpyxl,但看起来文件仍保持检查状态文件保存后输出..
我将不胜感激任何帮助。谢谢!
答案 0 :(得分:4)
haufe.sharepoint
仅适用于 sharepoint list ,但您可能需要访问文档库。
您应该在Sharepoint的Requests的帮助下使用Python REST API。
如果您的sharepoint网站不支持BasicAuth,我建议使用requests_ntlm
包。
由于其他原因,它对我不起作用,但也许它可以帮助你。
答案 1 :(得分:2)
首先,我将从本示例改编自Office365-REST-Python-Client的示例。它可以使用rest api在线与sharepoint一起使用。
您可能要上传到[baseurl] [site] [folder] [file]的示例URL。 https://your_company.sharepoint.com/path/to/site/Shared Documents / file.txt
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(url)
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()
答案 2 :(得分:2)
您可以使用 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')
答案 3 :(得分:1)
我想我回答这个问题可能有点晚了。
以下解决方案对我有用-
在Sharepoint网页上,转到“库工具” >>“库” >>“用Explorer命令打开”(它是“连接到Office”命令右下角的小图标。
地址栏为我们提供了将文件上传到的地址。 记住要从地址中删除“ http:”或“ https:” 。该地址是您上传文件的目的地。
随后,您可以使用Shutil包上传文件。
import shutil as sl
sl.copy(source,destination)
这应该有助于您将文件上传到Sharepoint
免责声明-在Python 3.6中效果很好
答案 4 :(得分:0)
我已经通过rest api调用在python中的SharePoint站点中创建了一个文件。请在下面找到我的代码。
def CreateHomePage():
server_relative_url = base_url+ '/_api/web/webinfos'
r1 = requests.get(server_relative_url, auth=HttpNtlmAuth(username, password), headers = headers, verify=True)
value = json.loads(r1.text)
for row in value['d']['results']:
if(row['Title'] == myvars['Site Name'].strip(' \t\n\r')):
Id= row['ServerRelativeUrl']
#Add Template and create file simultaneously
title = myvars['Site Name'].strip(' \t\n\r')
post_url = root_url +'GetFolderByServerRelativeUrl(\'/'+Id+'/Pages\')/Files/add(url=\'Home.aspx\',overwrite=true)'
r2 = requests.post(post_url, auth=HttpNtlmAuth(username, password), headers = headers, verify=True)
logger.debug("Creation of home page %d", r2.status_code)
答案 5 :(得分:0)
以上答案对我不起作用。 通过将驱动器映射到我的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:\\")
您也可以删除文件或执行类似普通文件夹的操作,而不是进行复制。
答案 6 :(得分:0)
我创建了一个脚本来将附件上传到SharePoint列表中 让我知道它是否有效
import requests
from shareplum import Office365
# Obtain auth cookie
authcookie = Office365('https://YOUR-NAME.sharepoint.com', username='YOUR-USERNAME',password='YOUR-PASSWORD').GetCookies()
session = requests.Session()
session.cookies = authcookie
session.headers.update({'user-agent': 'python_bite/v1'})
session.headers.update({'accept': 'application/json;odata=verbose'})
# dirty workaround.... I'm getting the X-RequestDigest from the first failed call
session.headers.update({'X-RequestDigest': 'FormDigestValue'})
response = session.post(url="https://YOUR-NAME.sharepoint.com/sites/YOU-SITE/_api/web/GetFolderByServerRelativeUrl('YOUR-FOLDER')/Files/add(url='a.txt',overwrite=true)",data="")
session.headers.update({'X-RequestDigest': response.headers['X-RequestDigest']})
# perform the upload
fileName = 'picture.png'
file_name = 'images.png'
with open(file_name, 'rb') as file_input:
response = session.post(
url="https://YOUR-NAME.sharepoint.com/sites/YOUR-SITE/_api/web/lists/getbytitle('ID-ROW-INTO-SHAREPOINT')/items(4)/AttachmentFiles/add(FileName='" + fileName + "')",data=file_input)
print(response.text)