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

如何为Python SharePoint add_item方法设置Content-Type并解决字段报错

解决SharePoint add_item时属性不存在的问题及请求头设置方案

问题根源

你遇到的ClientRequestException提示属性不存在,本质是SharePoint REST API在默认请求头(application/json)下会使用精简元数据模式,导致字段名称映射不匹配;而设置application/json;odata=verbose头后,API会切换到verbose模式,允许直接使用字段的内部名称(或正确的显示名称)提交数据。另外,SharePoint列表的字段内部名称可能和显示名称不一致,这也是触发该错误的常见原因。

针对不同Python SharePoint库的解决方案

1. 使用shareplum库

shareplum支持通过自定义Session全局设置请求头,确保add_item请求携带正确的Content-Type:

import requests
import pandas as pd
from shareplum import Site
from shareplum.site import Version

# 1. 创建带自定义请求头的Session
session = requests.Session()
session.headers.update({
    "Content-Type": "application/json;odata=verbose"
})
session.auth = ("你的用户名", "你的密码")

# 2. 连接到SharePoint站点
site = Site("https://你的域名.sharepoint.com/sites/你的站点", version=Version.v365, auth=session)

# 3. 获取目标列表
sp_list = site.List("Mahesh_Demo")

# 4. 截断现有数据(删除所有项)
existing_items = sp_list.get_items()
if existing_items:
    sp_list.delete_items([item["ID"] for item in existing_items])

# 5. 读取CSV并转换为字典列表
df = pd.read_csv("你的CSV文件路径.csv")
# 可选:验证字段映射,打印列表所有字段的显示名称和内部名称
# for field in sp_list.fields:
#     print(f"显示名称: {field['Title']}, 内部名称: {field['InternalName']}")
# 确保df的列名和SharePoint字段的内部名称一致,不一致则重命名
items_to_add = df.to_dict("records")

# 6. 批量添加数据
sp_list.add_items(items_to_add)

2. 使用office365-rest-python-client库

该库可通过修改客户端上下文的请求头来实现目标:

import pandas as pd
from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.user_credential import UserCredential

# 1. 初始化客户端上下文并设置请求头
ctx = ClientContext("https://你的域名.sharepoint.com/sites/你的站点").with_credentials(
    UserCredential("你的用户名", "你的密码")
)
# 添加verbose模式的Content-Type头
ctx._pending_request.headers["Content-Type"] = "application/json;odata=verbose"

# 2. 获取目标列表
sp_list = ctx.web.lists.get_by_title("Mahesh_Demo")
ctx.load(sp_list)
ctx.execute_query()

# 3. 截断现有数据
items = sp_list.get_items()
ctx.load(items)
ctx.execute_query()
for item in items:
    item.delete_object()
ctx.execute_query()

# 4. 读取CSV并逐行添加
df = pd.read_csv("你的CSV文件路径.csv")
# 注意:此处必须使用字段的内部名称
for _, row in df.iterrows():
    item_props = {
        "CATEGORY": row["CATEGORY"],
        # 其他字段按同样方式映射
    }
    sp_list.add_item(item_props)
    ctx.execute_query()

关键检查项

  • 字段内部名称验证:如果设置请求头后仍报错,优先检查是否误用了字段的显示名称而非内部名称。可通过SharePoint列表的「字段设置」页面查看内部名称,或用示例中注释的代码打印字段详情。
  • 权限验证:确保使用的账号对目标列表拥有编辑权限,避免因权限不足导致的隐性错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 18:45:38