Google Spreadsheets Python API - Simple interface for working with Google Sheets
Utility functions and helper classes for coordinate conversion, data processing, and working with spreadsheet elements.
Convert between A1 notation and row/column coordinates.
def a1_to_rowcol(label: str) -> Tuple[int, int]:
"""
Convert A1 notation to row/column coordinates.
Parameters:
- label (str): A1 notation cell address (e.g., "A1", "Z10", "AA5").
Returns:
Tuple[int, int]: Row and column as 1-indexed integers (row, col).
"""
def rowcol_to_a1(row: int, col: int) -> str:
"""
Convert row/column coordinates to A1 notation.
Parameters:
- row (int): Row number (1-indexed).
- col (int): Column number (1-indexed).
Returns:
str: A1 notation cell address.
"""
def column_letter_to_index(column: str) -> int:
"""
Convert column letter to index.
Parameters:
- column (str): Column letter (e.g., "A", "Z", "AA").
Returns:
int: Column index (1-indexed).
"""Work with ranges and range notation.
def absolute_range_name(sheet_name: str, range_name: str) -> str:
"""
Create absolute range name with sheet reference.
Parameters:
- sheet_name (str): Worksheet name.
- range_name (str): A1 notation range.
Returns:
str: Absolute range name (e.g., "'Sheet1'!A1:B10").
"""
def a1_range_to_grid_range(name: str, default_sheet_id: int = 0) -> Dict:
"""
Convert A1 notation range to grid range object.
Parameters:
- name (str): A1 notation range.
- default_sheet_id (int): Sheet ID if not specified in range. Default: 0.
Returns:
Dict: Grid range object with startRowIndex, endRowIndex, startColumnIndex, endColumnIndex.
"""
def is_full_a1_notation(range_name: str) -> bool:
"""
Check if range name includes sheet reference.
Parameters:
- range_name (str): Range name to check.
Returns:
bool: True if range includes sheet reference.
"""Convert and process cell values.
def numericise(value: str, default_blank: str = "", ignore: List[str] = None,
allow_underscores_in_numeric_literals: bool = False) -> Union[str, int, float]:
"""
Convert string values to appropriate numeric types.
Parameters:
- value (str): String value to convert.
- default_blank (str): Value to return for blank strings. Default: "".
- ignore (List[str], optional): List of strings to not convert.
- allow_underscores_in_numeric_literals (bool): Allow underscores in numbers. Default: False.
Returns:
Union[str, int, float]: Converted value (int, float, or original string).
"""
def to_records(values: List[List], keys: List[str] = None, **kwargs) -> List[Dict]:
"""
Convert 2D list to list of dictionaries.
Parameters:
- values (List[List]): 2D array of values.
- keys (List[str], optional): Keys for dictionaries. If None, uses first row.
- **kwargs: Additional arguments passed to record conversion.
Returns:
List[Dict]: List of dictionaries with keys as column headers.
"""Process and manipulate data structures.
def fill_gaps(values: List[List], rows: int = None, cols: int = None) -> List[List]:
"""
Fill gaps in 2D list to ensure rectangular shape.
Parameters:
- values (List[List]): 2D list with potential gaps.
- rows (int, optional): Target number of rows. If None, uses maximum row count.
- cols (int, optional): Target number of columns. If None, uses maximum column count.
Returns:
List[List]: Filled 2D list with consistent dimensions.
"""
def cell_list_to_rect(cell_list: List[Cell]) -> List[List[Cell]]:
"""
Convert list of Cell objects to rectangular 2D structure.
Parameters:
- cell_list (List[Cell]): List of Cell objects.
Returns:
List[List[Cell]]: 2D list of Cell objects arranged by row/column.
"""
def filter_dict_values(input_dict: Dict, filter_function: Callable) -> Dict:
"""
Filter dictionary values using provided function.
Parameters:
- input_dict (Dict): Input dictionary to filter.
- filter_function (Callable): Function to test each value.
Returns:
Dict: Filtered dictionary.
"""Extract identifiers from Google Sheets URLs.
def extract_id_from_url(url: str) -> str:
"""
Extract spreadsheet ID from Google Sheets URL.
Parameters:
- url (str): Google Sheets URL.
Returns:
str: Spreadsheet ID.
Raises:
NoValidUrlKeyFound: If URL doesn't contain valid spreadsheet ID.
"""
def get_gid_from_url(url: str) -> str:
"""
Extract worksheet GID from Google Sheets URL.
Parameters:
- url (str): Google Sheets URL with GID parameter.
Returns:
str: Worksheet GID.
"""Utility functions for data search and manipulation.
def finditem(func: Callable, seq: Iterable) -> Any:
"""
Find first item in sequence matching condition.
Parameters:
- func (Callable): Function to test each item.
- seq (Iterable): Sequence to search.
Returns:
Any: First matching item, or None if not found.
"""
def quote(value: str, safe: str = "", encoding: str = None, errors: str = None) -> str:
"""
URL encode string value.
Parameters:
- value (str): String to encode.
- safe (str): Characters not to encode. Default: "".
- encoding (str, optional): Character encoding.
- errors (str, optional): Error handling scheme.
Returns:
str: URL-encoded string.
"""Helper functions for processing and manipulating worksheet data.
def wid_to_gid(wid: str) -> str:
"""
Calculate gid of a worksheet from its wid.
Parameters:
- wid (str): Worksheet ID (wid).
Returns:
str: The calculated gid.
"""
def is_scalar(x: Any) -> bool:
"""
Return True if the value is scalar. A scalar is not a sequence but can be a string.
Parameters:
- x (Any): Value to check.
Returns:
bool: True if the value is scalar.
"""
def combined_merge_values(worksheet_metadata: Dict, values: List[List[Any]],
start_row_index: int, start_col_index: int) -> List[List[Any]]:
"""
For each merged region, replace all values with the value of the top-left cell of the region.
Parameters:
- worksheet_metadata (Dict): The metadata returned by the Google API for the worksheet.
- values (List[List[Any]]): The values matrix to process.
- start_row_index (int): Starting row index.
- start_col_index (int): Starting column index.
Returns:
List[List[Any]]: The processed values with merged regions replaced.
"""
def rightpad(row: List[Any], max_len: int, padding_value: Any = "") -> List[Any]:
"""
Right-pad a row to reach the specified length.
Parameters:
- row (List[Any]): The row to pad.
- max_len (int): The target length.
- padding_value (Any): Value to use for padding. Default: "".
Returns:
List[Any]: The padded row.
"""
def fill_gaps(L: List[List[Any]], rows: int = None, cols: int = None,
padding_value: Any = "") -> List[List[Any]]:
"""
Fill gaps in a list of lists to make it rectangular.
Parameters:
- L (List[List[Any]]): The list of lists to fill gaps in.
- rows (int, optional): Target number of rows.
- cols (int, optional): Target number of columns.
- padding_value (Any): Value to use for filling gaps. Default: "".
Returns:
List[List[Any]]: The filled matrix.
"""
def find_table(values: List[List[str]], start_range: str, direction: str = "table") -> List[List[str]]:
"""
Expands a list of values based on non-null adjacent cells.
Parameters:
- values (List[List[str]]): Values where to find the table.
- start_range (str): The starting cell range in A1 notation.
- direction (str): The expand direction ('right', 'down', or 'table'). Default: 'table'.
Returns:
List[List[str]]: The resulting matrix.
"""Color format conversion and processing.
def convert_colors_to_hex_value(input_dict_or_list: Union[Dict, List]) -> Union[Dict, List]:
"""
Convert color values to hexadecimal format.
Parameters:
- input_dict_or_list (Union[Dict, List]): Input containing color values.
Returns:
Union[Dict, List]: Input with colors converted to hex values.
"""Function decorators for parameter validation.
def accepted_kwargs(**kwargs) -> Callable:
"""
Decorator to validate accepted keyword arguments.
Parameters:
- **kwargs: Accepted keyword arguments and their types/validators.
Returns:
Callable: Decorator function.
"""class ExportFormat(Enum):
PDF = "pdf"
EXCEL = "xlsx"
ODS = "ods"
CSV = "csv"
TSV = "tsv"
ZIP = "zip"class Dimension(Enum):
ROWS = "ROWS"
COLUMNS = "COLUMNS"class ValueRenderOption(Enum):
FORMATTED_VALUE = "FORMATTED_VALUE"
UNFORMATTED_VALUE = "UNFORMATTED_VALUE"
FORMULA = "FORMULA"
class ValueInputOption(Enum):
RAW = "RAW"
USER_ENTERED = "USER_ENTERED"
class DateTimeRenderOption(Enum):
SERIAL_NUMBER = "SERIAL_NUMBER"
FORMATTED_STRING = "FORMATTED_STRING"class InsertDataOption(Enum):
OVERWRITE = "OVERWRITE"
INSERT_ROWS = "INSERT_ROWS"
class MergeType(Enum):
MERGE_ALL = "MERGE_ALL"
MERGE_COLUMNS = "MERGE_COLUMNS"
MERGE_ROWS = "MERGE_ROWS"class PasteType(Enum):
PASTE_NORMAL = "PASTE_NORMAL"
PASTE_VALUES = "PASTE_VALUES"
PASTE_FORMAT = "PASTE_FORMAT"
PASTE_NO_BORDERS = "PASTE_NO_BORDERS"
PASTE_FORMULA = "PASTE_FORMULA"
PASTE_DATA_VALIDATION = "PASTE_DATA_VALIDATION"
PASTE_CONDITIONAL_FORMATTING = "PASTE_CONDITIONAL_FORMATTING"
class PasteOrientation(Enum):
NORMAL = "NORMAL"
TRANSPOSE = "TRANSPOSE"
class DelimiterType(Enum):
COMMA = "COMMA"
SEMICOLON = "SEMICOLON"
PERIOD = "PERIOD"
SPACE = "SPACE"
CUSTOM = "CUSTOM"
AUTODETECT = "AUTODETECT"A1_ADDR_RE: Pattern
"""Regular expression for A1 cell addresses."""
A1_ADDR_FULL_RE: Pattern
"""Regular expression for full A1 addresses including sheet references."""class GridRange:
"""Grid range representation with start/end row/column indices."""
sheetId: int
startRowIndex: int
endRowIndex: int
startColumnIndex: int
endColumnIndex: int
class RowData:
"""Represents data for a single row."""
values: List[CellData]
class CellData:
"""Represents data for a single cell."""
userEnteredValue: ExtendedValue
effectiveValue: ExtendedValue
formattedValue: str
userEnteredFormat: CellFormat
effectiveFormat: CellFormat
class ExtendedValue:
"""Extended value supporting different data types."""
numberValue: float
stringValue: str
boolValue: bool
formulaValue: strclass Color:
"""RGB color representation."""
red: float # 0-1
green: float # 0-1
blue: float # 0-1
alpha: float # 0-1
class ColorStyle:
"""Color style with theme support."""
rgbColor: Color
themeColor: str
class TextFormat:
"""Text formatting specification."""
foregroundColor: ColorStyle
fontFamily: str
fontSize: int
bold: bool
italic: bool
strikethrough: bool
underline: bool
class NumberFormat:
"""Number formatting specification."""
type: str # "NUMBER", "CURRENCY", "PERCENT", etc.
pattern: str # Format pattern
class CellFormat:
"""Complete cell formatting specification."""
numberFormat: NumberFormat
backgroundColor: ColorStyle
textFormat: TextFormat
horizontalAlignment: str
verticalAlignment: str
wrapStrategy: str
textDirection: str# Convert coordinates
row, col = gspread.utils.a1_to_rowcol('B5') # (5, 2)
cell_addr = gspread.utils.rowcol_to_a1(5, 2) # 'B5'
# Process data
values = [['Name', 'Age'], ['Alice', '25'], ['Bob', '30']]
records = gspread.utils.to_records(values)
# [{'Name': 'Alice', 'Age': 25}, {'Name': 'Bob', 'Age': 30}]
# Extract spreadsheet ID from URL
url = 'https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit'
sheet_id = gspread.utils.extract_id_from_url(url)
# Fill gaps in data
sparse_data = [['A', 'B'], ['C']]
filled_data = gspread.utils.fill_gaps(sparse_data)
# [['A', 'B'], ['C', '']]
# Use enums
from gspread.utils import ValueRenderOption, MergeType
worksheet.get_all_values(value_render_option=ValueRenderOption.UNFORMATTED_VALUE)
worksheet.merge_cells('A1:B2', merge_type=MergeType.MERGE_COLUMNS)Install with Tessl CLI
npx tessl i tessl/pypi-gspread