You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确格式化Graph API请求以更新SharePoint中Excel单元格

使用Microsoft Graph API更新SharePoint Excel单元格值时的400错误问题

我需要通过Microsoft Graph API更新SharePoint托管的Excel单元格值,参考官方文档操作。之前用类似格式成功完成过格式更新、清除单元格等API调用,但这次操作出现问题:尝试向'Plant_3'工作表的B17单元格写入"41373"时,代码返回400错误,错误信息如下:

"code": "InvalidAuthenticationToken",
"message": "Access token is empty."

这个提示应该是通用错误,实际并非认证问题——因为其他Graph API调用使用相同的ID和密钥都能正常工作,推测是API请求格式有误。

代码示例

def graph_config_params():
    """
    read authentication parameters from config file, return dict with results
    :return: (dict) configuration parameters
    """
    try:
        # Read the config file
        config = configparser.ConfigParser()
        config.read('config.ini')
        # assign authorization tokens from config file to variables
        return_dict = {'client_id': config['entra_auth']['client_id'],
                       'client_secret': config['entra_auth']['client_secret'],
                       'tenant_id': config['entra_auth']['tenant_id'],
                       # Get necessary configuration data for the SharePoint file
                       'site_id': config['site']['site_id'],
                       'document_library_id': config['site']['document_library_id'],
                       'doc_id': config['site']['doc_id'],
                       'drive_id': config['site']['drive_id']}
        return return_dict
    except Exception as e:
        log.exception(e)    

def set_up_ms_graph_authentication(graph_auth_args=graph_config_params()):
    """
    Create headers with access token for Microsoft Graph API to authenticate
    :param graph_authentication_params:
    :return: (dict) headers with access token
    """
    try:
        # Set up Microsoft Graph authentication
        msal_scope = ['https://graph.microsoft.com/.default']
        msal_app = ConfidentialClientApplication(
            client_id=graph_auth_args['client_id'],
            authority=f"https://login.microsoftonline.com/{graph_auth_args['tenant_id']}",
            client_credential=graph_auth_args['client_secret'])
        result = msal_app.acquire_token_silent(scopes=msal_scope,
                                               account=None)
        if not result:
            result = msal_app.acquire_token_for_client(scopes=msal_scope)
        if 'access_token' in result:
            access_token = result['access_token']
        else:
            raise Exception("Failed to acquire token")
        # Prepare request headers with the acquired access token
        headers = {'Authorization': f'Bearer {access_token}'}
        # log.info(f'headers: {headers}')
        return headers
    except Exception as e:
        log.exception(e)    

sheet = 'Plant_3'
# get variables that work in other Graph API calls
config_args=graph_config_params()
# get Authorization Bearer token, again works in other Graph API calls.
my_headers = set_up_ms_graph_authentication()
url=  f"https://graph.microsoft.com/v1.0/sites/{config_args['site_id']}/drives/{config_args['drive_id']}/items/{config_args['doc_id']}/workbook/worksheets/{sheet}/range/(address='B:17')"
response = requests.patch(url,
                          headers=my_headers,
                          json={'values': [['41373']] })

已尝试的解决方法

  • 将请求的关键字参数从json改为data
  • 在json和data参数中,为'41373'使用单括号或不使用括号
  • 验证权限:移除Files.ReadWrite.All后出现403错误,说明权限本身没问题
  • 将请求方法从patch改为post,并尝试上述所有配置
  • 添加valueType参数,设置为[['String']]

目前仍未解决,寻求针对该请求格式问题的解决方案。

内容的提问来源于stack exchange,提问作者Python_Learner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 02:31:08