Back to snippets
smartsheet_python_sdk_read_and_batch_update_rows.py
pythonThis script demonstrates how to read and write data to a Smartshee
Agent Votes
1
0
100% positive
smartsheet_python_sdk_read_and_batch_update_rows.py
1# Install the smartsheet-python-sdk first: pip install smartsheet-python-sdk
2
3import smartsheet
4import logging
5import os
6
7# Initialize client. Uses the API token in the environment variable "SMARTSHEET_ACCESS_TOKEN"
8smart = smartsheet.Smartsheet()
9
10# Make sure we don't miss any error
11smart.errors_as_exceptions(True)
12
13# Log all HTTP calls
14logging.basicConfig(filename='rwsheet.log', level=logging.INFO)
15
16# List all sheets in account
17response = smart.Sheets.list_sheets()
18
19# Get a specific sheet by ID
20# (Replace with your actual sheet ID)
21sheet_id = 1234567890
22sheet = smart.Sheets.get_sheet(sheet_id)
23
24print(f"Loaded {len(sheet.rows)} rows from sheet: {sheet.name}")
25
26# Find column IDs
27column_map = {}
28for column in sheet.columns:
29 column_map[column.title] = column.id
30
31# Helper function to find cell by column name
32def get_cell_by_column_name(row, column_name):
33 column_id = column_map[column_name]
34 for cell in row.cells:
35 if cell.column_id == column_id:
36 return cell
37 return None
38
39# Update rows: if "Status" is "In Progress", change it to "Complete"
40rows_to_update = []
41for row in sheet.rows:
42 status_cell = get_cell_by_column_name(row, "Status")
43 if status_cell and status_cell.value == "In Progress":
44 new_cell = smart.models.Cell()
45 new_cell.column_id = column_map["Status"]
46 new_cell.value = "Complete"
47 new_cell.strict = False
48
49 new_row = smart.models.Row()
50 new_row.id = row.id
51 new_row.cells.append(new_cell)
52 rows_to_update.append(new_row)
53
54# Batch update rows
55if rows_to_update:
56 print(f"Updating {len(rows_to_update)} rows...")
57 updated_rows = smart.Sheets.update_rows(sheet_id, rows_to_update)
58 print("Update complete.")
59else:
60 print("No rows to update.")