冉冉说
这是通过 Python 连接到共享点以及访问文件列表、文件夹和 Sharepoint 的单个文件内容的入门代码。您可以在此基础上进行构建以满足您的需求。请注意,此方法适用于可通过 Internet 访问的公共 Sharepoint 站点。对于托管在公司 Intranet 上的组织受限 Sharepoint 站点,我尚未测试此代码。您将不得不稍微修改 Sharepoint 文件的链接,因为您无法使用从 Web 浏览器复制的文件的 URL 地址直接访问 Python 中的 Sharepoint 文件。from office365.runtime.auth.authentication_context import AuthenticationContextfrom office365.sharepoint.client_context import ClientContextfrom office365.sharepoint.files.file import File ####inputs######### This will be the URL that points to your sharepoint site. # Make sure you change only the parts of the link that start with "Your"url_shrpt = 'https://YourOrganisation.sharepoint.com/sites/YourSharepointSiteName'username_shrpt = 'YourUsername'password_shrpt = 'YourPassword'folder_url_shrpt = '/sites/YourSharepointSiteName/Shared%20Documents/YourSharepointFolderName/'##########################Authentication###For authenticating into your sharepoint site###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() print('Authenticated into sharepoint as: ',web.properties['Title'])else: print(ctx_auth.get_last_error())############################ ####Function for extracting the file names of a folder in sharepoint######If you want to extract the folder names instead of file names, you have to change "sub_folders = folder.files" to "sub_folders = folder.folders" in the below functionglobal print_folder_contentsdef print_folder_contents(ctx, folder_url): try: folder = ctx.web.get_folder_by_server_relative_url(folder_url) fold_names = [] sub_folders = folder.files #Replace files with folders for getting list of folders ctx.load(sub_folders) ctx.execute_query() for s_folder in sub_folders: fold_names.append(s_folder.properties["Name"]) return fold_names except Exception as e: print('Problem printing out library contents: ', e)###################################################### # Call the function by giving your folder URL as input filelist_shrpt=print_folder_contents(ctx,folder_url_shrpt) #Print the list of files present in the folderprint(filelist_shrpt)现在我们能够检索和打印 Sharepoint 中特定文件夹中存在的文件列表,下面是访问特定文件的文件内容并将其保存到知道 Sharepoint 中的文件名和路径的本地磁盘的代码。#Specify the URL of the sharepoint file. Remember to change only the the parts of the link that start with "Your"file_url_shrpt = '/sites/YourSharepointSiteName/Shared%20Documents/YourSharepointFolderName/YourSharepointFileName'#Load the sharepoint file content to "response" variableresponse = File.open_binary(ctx, file_url_shrpt)#Save the file to your offline pathwith open("Your_Offline_File_Path", 'wb') as output_file: output_file.write(response.content)您可以参考以下链接连接到 SQL Server 并将内容存储在表中: 使用 Python 连接到 Microsoft SQL Serverhttps://datatofish.com/how-to-connect-python-to-sql-server-using-pyodbc/