首页 > 解决方案 > 将多个csv文件上传到python中的sharepoint文件夹?

问题描述

我正在尝试将从PostgreSQLdb 中提取的数据保存到指定的 MS SharePoint 文件夹中。为此,首先我从本地数据库中检索数据,然后我需要将此数据存储/保存到 SharePoint 文件夹中。我尝试使用office365api 来执行此操作,但 SharePoint 文件夹中没有保存数据。有没有人在python中有类似的经验?在 python 中执行此操作的任何解决方法?有什么想法吗?

我目前的尝试

首先,我确实从本地 postgresql 数据库中提取数据,如下所示:

from sqlalchemy import create_engine
import pandas as pd
import os.path

hostname = 'localhost'
database_name = 'postgres'
user = 'kim'
pw = 'password123'

engine = create_engine('postgresql+psycopg2://'+user+':'+pw+'@'+hostname+'/'+database_name)

sql = """ select * from mytable """

with engine.connect() as conn:
    df = pd.read_sql_query(sql,con=engine)

然后,我尝试将数据存储/保存到指定的共享点文件夹,如下所示:

from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File 

url_shrpt = 'https://xyzcompany.sharepoint.com/_layouts/15/sharepoint.aspx?'
username_shrpt = 'kim@xyzcompany.com'
password_shrpt = 'password123'
folder_url_shrpt = 'https://xyzcompany.sharepoint.com/:f:/g/EnIh9jxkDVpOsTnAUbo-LvIBdsN0X_pJifX4_9Rx3rchnQ'

ctx_auth = AuthenticationContext(url_shrpt)
if ctx_auth.acquire_token_for_user(username_shrpt, password_shrpt):
    ctx = ClientContext(url_shrpt, ctx_auth)
    web = ctx.web
    ctx.load(web)
    ctx.execute_query()

else:
    print(ctx_auth.get_last_error())

response = File.open_binary(ctx, df)

with open("Your_Offline_File_Path", 'wb') as output_file:  
    output_file.write(response.content)

但文件未保存在 SharePoint 文件夹中。我们应该如何使用 python 将 PostgreSQL 中的数据保存到 SharePoint 文件夹中?有什么解决方法可以做到这一点吗?有什么想法吗?

目标

我想将从 PostgreSQL 数据库中提取的数据写到 SharePoint 文件夹中。从我目前的尝试来看,上述尝试没有将数据保存到 sharepoint 文件夹中。任何人都可以建议这样做的可能方式吗?

标签: pythonpostgresqlsharepointsqlalchemy

解决方案


我认为您应该在本地编写 csv 文件,然后尝试以下操作以将它们上传到 SharePoint 文件夹:

from shareplum import Site
from shareplum import Office365
from requests_ntlm import HttpNtlmAuth
from shareplum.site import Version

UN = "myself@xyzcompany.com"
PW = "hello#"

cred = HttpNtlmAuth(UN,PW)
authcookie = Office365('https://xyzcompany.sharepoint.com',username=UN,password=PW).GetCookies()
site = Site('https://xyzcompany.sharepoint.com/sites/sample_data/',version=Version.v365,authcookie=authcookie)
folder = site.Folder('Shared Documents/New Folder')

files = Path(os.getcwd()).glob('*.csv')
for file in files:
    with open(file, mode='rb') as rowFile:
        fileContent = rowFile.read()
    folder.upload_file(fileContent, os.path.basename(file))

这是无错误且有效的解决方案,这应该适用于将文件上传到 SharePoint 文件夹。


推荐阅读