Description
I'm trying to add headers to an existing Sharepoint list but I received the error message:
'dict' object has no attribute 'FieldTypeKind'
The code I'm using is the following:
import pandas as pd
from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.user_credential import UserCredential
SharePoint credentials
USERNAME = username
PASSWORD = password
SITE_URL = site_url
Excel file path
EXCEL_FILE_PATH = excel_file_path
Existing SharePoint list name
EXISTING_LIST_NAME = "Listname"
def connect_to_sharepoint(site_url, username, password):
"""
Authenticate and connect to SharePoint.
"""
try:
ctx = ClientContext(site_url).with_credentials(UserCredential(username, password))
print(f"Connected to SharePoint site: {site_url}")
return ctx
except Exception as e:
print(f"Error connecting to SharePoint: {e}")
return None
def add_missing_columns(sp_list, df_columns, existing_field_names):
"""
Add missing columns to the SharePoint list based on the Excel file headers.
"""
for column in df_columns:
if column not in existing_field_names:
print(f"Adding missing column '{column}'...")
try:
# Define the field payload
field_payload = {
"__metadata": {"type": "SP.FieldText"},
"Title": column,
"FieldTypeKind": 2, # 2 corresponds to 'Text' field type
}
sp_list.fields.add(field_payload).execute_query()
print(f"Column '{column}' created successfully.")
except Exception as e:
print(f"Error creating column '{column}': {e}")
else:
print(f"Column '{column}' already exists. Skipping...")
def main():
"""
Main function to execute the SharePoint data upload process.
"""
# Connect to SharePoint
ctx = connect_to_sharepoint(SITE_URL, USERNAME, PASSWORD)
if ctx is None:
return
try:
# Access the existing SharePoint list
sp_list = ctx.web.lists.get_by_title(EXISTING_LIST_NAME)
print(f"List '{EXISTING_LIST_NAME}' exists. Validating and adding columns...")
# Retrieve existing fields in the SharePoint list
existing_fields = sp_list.fields.get().execute_query()
print("Got existing fields")
existing_field_names = [field.properties["Title"] for field in existing_fields]
print(f"Existing fields in the list: {existing_field_names}")
# Add missing columns dynamically
add_missing_columns(sp_list, df.columns, existing_field_names)
except Exception as e:
print(f"Error: {e}")
if name == "main":
main()