简体   繁体   中英

Manipulate Excel file on Sharepoint Python

I am attempting to open, read and use a macro and then re save an Excel file on Sharepoint using Python. Using the Office 365 REST-Python Client I can open and read but struggling to see how to do the rest.

Would appreciate any help, thanks!

`ctx_auth = AuthenticationContext(url)
if ctx_auth.acquire_token_for_user(username, password):
    ctx = ClientContext(url, ctx_auth)
    web = ctx.web
    ctx.load(web)
    ctx.execute_query()
    response = File.open_binary(ctx, relative_url)
    #save data to BytesIO stream
    bio = io.BytesIO()
    bio.write(response.content)
    bio.seek(0) #set file object to start

    #read file into pandas dataframe
    df = pd.read_excel(bio, sheet_name="Overview")
    print(df)
    df.at[0,"Unnamed: 1"] = "description"

    bio2 = io.BytesIO()

    #pip install xlsxwriter
    writer = pd.ExcelWriter(bio2)
    df.to_excel(writer, sheet_name="Overview")
    writer.save()
    bio2.seek(0)
    df = pd.read_excel(bio2, sheet_name="Overview")
    workbook = bio2.read()
    response2 = File.save_binary(ctx, relative_url, workbook)
    print(response2)`

You can refer to the following Python script to save and read Excel files on Sharepoint.

#import all the libraries
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File 
import io
import pandas as pd

#target url taken from sharepoint and credentials
url = 'https://company.sharepoint.com/user/folder'
path = '/user/folder/Documents/Target_Excel_File_v4.xlsx'
username = 'Dumby_account@company.com'
password = 'Password!'

ctx_auth = AuthenticationContext(url)
if ctx_auth.acquire_token_for_user(username, password):
  ctx = ClientContext(url, ctx_auth)
  web = ctx.web
  ctx.load(web)
  ctx.execute_query()
  print("Authentication successful")

response = File.open_binary(ctx, path)

#save data to BytesIO stream
bytes_file_obj = io.BytesIO()
bytes_file_obj.write(response.content)
bytes_file_obj.seek(0) #set file object to start

#read excel file and each sheet into pandas dataframe 
df = pd.read_excel(bytes_file_obj, sheet_name = None)
print(df)

There is a similar SO threading problem here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM