index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
708,032
port_for.store
bound_ports
List all bound ports.
def bound_ports(self) -> List[Tuple[str, int]]: """List all bound ports.""" return [ (app, int(port)) for app, port in self._get_parser().items(DEFAULTSECT) ]
(self) -> List[Tuple[str, int]]
708,033
port_for.store
unbind_port
Remove port assignement to application.
def unbind_port(self, app: str) -> None: """Remove port assignement to application.""" parser = self._get_parser() parser.remove_option(DEFAULTSECT, app) self._save(parser)
(self, app: str) -> NoneType
708,036
port_for.api
available_good_ports
List available good ports.
def available_good_ports(min_range_len: int = 20, border: int = 3) -> Set[int]: """List available good ports.""" return utils.ranges_to_set( good_port_ranges(min_range_len=min_range_len, border=border) )
(min_range_len: int = 20, border: int = 3) -> Set[int]
708,037
port_for.api
available_ports
Return a set of possible ports. .. note:: Excluding system, ephemeral and well-known ports. Pass ``high`` and/or ``low`` to limit the port range.
def available_ports( low: int = 1024, high: int = 65535, exclude_ranges: Optional[List[Tuple[int, int]]] = None, ) -> Set[int]: """Return a set of possible ports. .. note:: Excluding system, ephemeral and well-known ports. Pass ``high`` and/or ``low`` to limit the port range. """ if exclude_ranges is None: exclude_ranges = [] available = utils.ranges_to_set(UNASSIGNED_RANGES) exclude = utils.ranges_to_set( # Motivation behind excluding ephemeral port ranges: # let's say you decided to use an ephemeral local port # as a persistent port, and "reserve" it to your software. # OS won't know about it, and still can try to use this port. # This is not a problem if your service is always running and occupying # this port (OS would pick next one). But if the service is temporarily # not using the port (because of restart of other reason), # OS might reuse the same port, # which might prevent the service from starting. ephemeral.port_ranges() + exclude_ranges + [SYSTEM_PORT_RANGE, (SYSTEM_PORT_RANGE[1], low), (high, 65536)] ) return available.difference(exclude)
(low: int = 1024, high: int = 65535, exclude_ranges: Optional[List[Tuple[int, int]]] = None) -> Set[int]
708,040
port_for.api
get_port
Retun a random available port. If there's only one port passed (e.g. 5000 or '5000') function does not check if port is available. If there's -1 passed as an argument, function returns None. :param ports: exact port (e.g. '8000', 8000) randomly selected port (None) - any random available port [(2000,3000)] or (2000,3000) - random available port from a given range [{4002,4003}] or {4002,4003} - random of 4002 or 4003 ports [(2000,3000), {4002,4003}] -random of given range and set :param exclude_ports: A set of known ports that can not be selected. :returns: a random free port :raises: ValueError
def get_port( ports: Optional[PortType], exclude_ports: Optional[Iterable[int]] = None, ) -> Optional[int]: """Retun a random available port. If there's only one port passed (e.g. 5000 or '5000') function does not check if port is available. If there's -1 passed as an argument, function returns None. :param ports: exact port (e.g. '8000', 8000) randomly selected port (None) - any random available port [(2000,3000)] or (2000,3000) - random available port from a given range [{4002,4003}] or {4002,4003} - random of 4002 or 4003 ports [(2000,3000), {4002,4003}] -random of given range and set :param exclude_ports: A set of known ports that can not be selected. :returns: a random free port :raises: ValueError """ if ports == -1: return None elif not ports: return select_random(None, exclude_ports) try: return int(ports) # type: ignore[arg-type] except TypeError: pass ports_set: Set[int] = set() try: if not isinstance(ports, list): ports = [ports] ranges: Set[int] = utils.ranges_to_set( filter_by_type(ports, tuple) # type: ignore[arg-type] ) nums: Set[int] = set(filter_by_type(ports, int)) sets: Set[int] = set( chain( *filter_by_type( ports, (set, frozenset) # type: ignore[arg-type] ) ) ) ports_set = ports_set.union(ranges, sets, nums) except ValueError: raise PortForException( "Unknown format of ports: %s.\n" 'You should provide a ports range "[(4000,5000)]"' 'or "(4000,5000)" or a comma-separated ports set' '"[{4000,5000,6000}]" or list of ints "[400,5000,6000,8000]"' 'or all of them "[(20000, 30000), {48889, 50121}, 4000, 4004]"' % (ports,) ) return select_random(ports_set, exclude_ports)
(ports: Union[str, int, Tuple[int, int], Set[int], List[str], List[int], List[Tuple[int, int]], List[Set[int]], List[Union[Set[int], Tuple[int, int]]], List[Union[str, int, Tuple[int, int], Set[int]]], NoneType], exclude_ports: Optional[Iterable[int]] = None) -> Optional[int]
708,041
port_for.api
good_port_ranges
Return a list of 'good' port ranges. Such ranges are large and don't contain ephemeral or well-known ports. Ranges borders are also excluded.
def good_port_ranges( ports: Optional[Set[int]] = None, min_range_len: int = 20, border: int = 3 ) -> List[Tuple[int, int]]: """Return a list of 'good' port ranges. Such ranges are large and don't contain ephemeral or well-known ports. Ranges borders are also excluded. """ min_range_len += border * 2 if ports is None: ports = available_ports() ranges = utils.to_ranges(list(ports)) lenghts = sorted([(r[1] - r[0], r) for r in ranges], reverse=True) long_ranges = [ length[1] for length in lenghts if length[0] >= min_range_len ] without_borders = [ (low + border, high - border) for low, high in long_ranges ] return without_borders
(ports: Optional[Set[int]] = None, min_range_len: int = 20, border: int = 3) -> List[Tuple[int, int]]
708,042
port_for.api
is_available
Return if port is good to choose.
def is_available(port: int) -> bool: """Return if port is good to choose.""" return port in available_ports() and not port_is_used(port)
(port: int) -> bool
708,043
port_for.api
port_is_used
Return if port is used. Port is considered used if the current process can't bind to it or the port doesn't refuse connections.
def port_is_used(port: int, host: str = "127.0.0.1") -> bool: """Return if port is used. Port is considered used if the current process can't bind to it or the port doesn't refuse connections. """ unused = _can_bind(port, host) and _refuses_connection(port, host) return not unused
(port: int, host: str = '127.0.0.1') -> bool
708,044
port_for.api
select_random
Return random unused port number.
def select_random( ports: Optional[Set[int]] = None, exclude_ports: Optional[Iterable[int]] = None, ) -> int: """Return random unused port number.""" if ports is None: ports = available_good_ports() if exclude_ports is None: exclude_ports = set() ports.difference_update(set(exclude_ports)) for port in random.sample(tuple(ports), min(len(ports), 100)): if not port_is_used(port): return port raise PortForException("Can't select a port")
(ports: Optional[Set[int]] = None, exclude_ports: Optional[Iterable[int]] = None) -> int
708,102
num2words
num2words
null
def num2words(number, ordinal=False, lang='en', to='cardinal', **kwargs): # We try the full language first if lang not in CONVERTER_CLASSES: # ... and then try only the first 2 letters lang = lang[:2] if lang not in CONVERTER_CLASSES: raise NotImplementedError() converter = CONVERTER_CLASSES[lang] if isinstance(number, str): number = converter.str_to_number(number) # backwards compatible if ordinal: to = 'ordinal' if to not in CONVERTES_TYPES: raise NotImplementedError() return getattr(converter, 'to_{}'.format(to))(number, **kwargs)
(number, ordinal=False, lang='en', to='cardinal', **kwargs)
708,104
gspread.http_client
BackOffHTTPClient
BackoffClient is a gspread client with exponential backoff retries. In case a request fails due to some API rate limits, it will wait for some time, then retry the request. This can help by trying the request after some time and prevent the application from failing (by raising an APIError exception). .. Warning:: This Client is not production ready yet. Use it at your own risk ! .. note:: To use with the `auth` module, make sure to pass this backoff client factory using the ``client_factory`` parameter of the method used. .. note:: Currently known issues are: * will retry exponentially even when the error should raise instantly. Due to the Drive API that raises 403 (Forbidden) errors for forbidden access and for api rate limit exceeded.
class BackOffHTTPClient(HTTPClient): """BackoffClient is a gspread client with exponential backoff retries. In case a request fails due to some API rate limits, it will wait for some time, then retry the request. This can help by trying the request after some time and prevent the application from failing (by raising an APIError exception). .. Warning:: This Client is not production ready yet. Use it at your own risk ! .. note:: To use with the `auth` module, make sure to pass this backoff client factory using the ``client_factory`` parameter of the method used. .. note:: Currently known issues are: * will retry exponentially even when the error should raise instantly. Due to the Drive API that raises 403 (Forbidden) errors for forbidden access and for api rate limit exceeded.""" _HTTP_ERROR_CODES: List[HTTPStatus] = [ HTTPStatus.REQUEST_TIMEOUT, # in case of a timeout HTTPStatus.TOO_MANY_REQUESTS, # sheet API usage rate limit exceeded ] _NR_BACKOFF: int = 0 _MAX_BACKOFF: int = 128 # arbitrary maximum backoff def request(self, *args: Any, **kwargs: Any) -> Response: # Check if we should retry the request def _should_retry( code: int, error: Mapping[str, Any], wait: int, ) -> bool: # Drive API return a dict object 'errors', the sheet API does not if "errors" in error: # Drive API returns a code 403 when reaching quotas/usage limits if ( code == HTTPStatus.FORBIDDEN and error["errors"][0]["domain"] == "usageLimits" ): return True # We retry if: # - the return code is one of: # - 429: too many requests # - 408: request timeout # - >= 500: some server error # - AND we did not reach the max retry limit return ( code in self._HTTP_ERROR_CODES or code >= HTTPStatus.INTERNAL_SERVER_ERROR ) and wait <= self._MAX_BACKOFF try: return super().request(*args, **kwargs) except APIError as err: code = err.code error = err.error self._NR_BACKOFF += 1 wait = min(2**self._NR_BACKOFF, self._MAX_BACKOFF) # check if error should retry if _should_retry(code, error, wait) is True: time.sleep(wait) # make the request again response = self.request(*args, **kwargs) # reset counters for next time self._NR_BACKOFF = 0 return response # failed too many times, raise APIEerror raise err
(auth: google.auth.credentials.Credentials, session: Optional[requests.sessions.Session] = None) -> None
708,105
gspread.http_client
__init__
null
def __init__(self, auth: Credentials, session: Optional[Session] = None) -> None: if session is not None: self.session = session else: self.auth: Credentials = convert_credentials(auth) self.session = AuthorizedSession(self.auth) self.timeout: Optional[Union[float, Tuple[float, float]]] = None
(self, auth: google.auth.credentials.Credentials, session: Optional[requests.sessions.Session] = None) -> NoneType
708,106
gspread.http_client
batch_update
Lower-level method that directly calls `spreadsheets/<ID>:batchUpdate <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate>`_. :param dict body: `Batch Update Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate#request-body>`_. :returns: `Batch Update Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate#response-body>`_. :rtype: dict .. versionadded:: 3.0
def batch_update(self, id: str, body: Optional[Mapping[str, Any]]) -> Any: """Lower-level method that directly calls `spreadsheets/<ID>:batchUpdate <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate>`_. :param dict body: `Batch Update Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate#request-body>`_. :returns: `Batch Update Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate#response-body>`_. :rtype: dict .. versionadded:: 3.0 """ r = self.request("post", SPREADSHEET_BATCH_UPDATE_URL % id, json=body) return r.json()
(self, id: str, body: Optional[Mapping[str, Any]]) -> Any
708,107
gspread.http_client
export
Export the spreadsheet in the given format. :param str file_id: The key of the spreadsheet to export :param str format: The format of the resulting file. Possible values are: * ``ExportFormat.PDF`` * ``ExportFormat.EXCEL`` * ``ExportFormat.CSV`` * ``ExportFormat.OPEN_OFFICE_SHEET`` * ``ExportFormat.TSV`` * ``ExportFormat.ZIPPED_HTML`` See `ExportFormat`_ in the Drive API. :type format: :class:`~gspread.utils.ExportFormat` :returns bytes: The content of the exported file. .. _ExportFormat: https://developers.google.com/drive/api/guides/ref-export-formats
def export(self, file_id: str, format: str = ExportFormat.PDF) -> bytes: """Export the spreadsheet in the given format. :param str file_id: The key of the spreadsheet to export :param str format: The format of the resulting file. Possible values are: * ``ExportFormat.PDF`` * ``ExportFormat.EXCEL`` * ``ExportFormat.CSV`` * ``ExportFormat.OPEN_OFFICE_SHEET`` * ``ExportFormat.TSV`` * ``ExportFormat.ZIPPED_HTML`` See `ExportFormat`_ in the Drive API. :type format: :class:`~gspread.utils.ExportFormat` :returns bytes: The content of the exported file. .. _ExportFormat: https://developers.google.com/drive/api/guides/ref-export-formats """ if format not in ExportFormat: raise UnSupportedExportFormat url = "{}/{}/export".format(DRIVE_FILES_API_V3_URL, file_id) params: ParamsType = {"mimeType": format} r = self.request("get", url, params=params) return r.content
(self, file_id: str, format: str = <ExportFormat.PDF: 'application/pdf'>) -> bytes
708,108
gspread.http_client
fetch_sheet_metadata
Similar to :method spreadsheets_get:`gspread.http_client.spreadsheets_get`, get the spreadsheet form the API but by default **does not get the cells data**. It only retrieve the the metadata from the spreadsheet. :param str id: the spreadsheet ID key :param dict params: (optional) the HTTP params for the GET request. By default sets the parameter ``includeGridData`` to ``false``. :returns: The raw spreadsheet :rtype: dict
def fetch_sheet_metadata(self, id: str, params: Optional[ParamsType] = None) -> Any: """Similar to :method spreadsheets_get:`gspread.http_client.spreadsheets_get`, get the spreadsheet form the API but by default **does not get the cells data**. It only retrieve the the metadata from the spreadsheet. :param str id: the spreadsheet ID key :param dict params: (optional) the HTTP params for the GET request. By default sets the parameter ``includeGridData`` to ``false``. :returns: The raw spreadsheet :rtype: dict """ if params is None: params = {"includeGridData": "false"} url = SPREADSHEET_URL % id r = self.request("get", url, params=params) return r.json()
(self, id: str, params: Optional[MutableMapping[str, Union[str, int, bool, float, List[str], NoneType]]] = None) -> Any
708,109
gspread.http_client
get_file_drive_metadata
Get the metadata from the Drive API for a specific file This method is mainly here to retrieve the create/update time of a file (these metadata are only accessible from the Drive API).
def get_file_drive_metadata(self, id: str) -> Any: """Get the metadata from the Drive API for a specific file This method is mainly here to retrieve the create/update time of a file (these metadata are only accessible from the Drive API). """ url = DRIVE_FILES_API_V3_URL + "/{}".format(id) params: ParamsType = { "supportsAllDrives": True, "includeItemsFromAllDrives": True, "fields": "id,name,createdTime,modifiedTime", } res = self.request("get", url, params=params) return res.json()
(self, id: str) -> Any
708,110
gspread.http_client
import_csv
Imports data into the first page of the spreadsheet. :param str data: A CSV string of data. Example: .. code:: # Read CSV file contents content = open('file_to_import.csv', 'r').read() gc.import_csv(spreadsheet.id, content) .. note:: This method removes all other worksheets and then entirely replaces the contents of the first worksheet.
def import_csv(self, file_id: str, data: Union[str, bytes]) -> Any: """Imports data into the first page of the spreadsheet. :param str data: A CSV string of data. Example: .. code:: # Read CSV file contents content = open('file_to_import.csv', 'r').read() gc.import_csv(spreadsheet.id, content) .. note:: This method removes all other worksheets and then entirely replaces the contents of the first worksheet. """ # Make sure we send utf-8 if isinstance(data, str): data = data.encode("utf-8") headers = {"Content-Type": "text/csv"} url = "{}/{}".format(DRIVE_FILES_UPLOAD_API_V2_URL, file_id) res = self.request( "put", url, data=data, params={ "uploadType": "media", "convert": True, "supportsAllDrives": True, }, headers=headers, ) return res.json()
(self, file_id: str, data: Union[str, bytes]) -> Any
708,111
gspread.http_client
insert_permission
Creates a new permission for a file. :param str file_id: a spreadsheet ID (aka file ID). :param email_address: user or group e-mail address, domain name or None for 'anyone' type. :type email_address: str, None :param str perm_type: (optional) The account type. Allowed values are: ``user``, ``group``, ``domain``, ``anyone`` :param str role: (optional) The primary role for this user. Allowed values are: ``owner``, ``writer``, ``reader`` :param bool notify: Whether to send an email to the target user/domain. Default ``True``. :param str email_message: (optional) An email message to be sent if ``notify=True``. :param bool with_link: Whether the link is required for this permission to be active. Default ``False``. :returns dict: the newly created permission Examples:: # Give write permissions to otto@example.com gc.insert_permission( '0BmgG6nO_6dprnRRUWl1UFE', 'otto@example.org', perm_type='user', role='writer' ) # Make the spreadsheet publicly readable gc.insert_permission( '0BmgG6nO_6dprnRRUWl1UFE', None, perm_type='anyone', role='reader' )
def insert_permission( self, file_id: str, email_address: Optional[str], perm_type: Optional[str], role: Optional[str], notify: bool = True, email_message: Optional[str] = None, with_link: bool = False, ) -> Response: """Creates a new permission for a file. :param str file_id: a spreadsheet ID (aka file ID). :param email_address: user or group e-mail address, domain name or None for 'anyone' type. :type email_address: str, None :param str perm_type: (optional) The account type. Allowed values are: ``user``, ``group``, ``domain``, ``anyone`` :param str role: (optional) The primary role for this user. Allowed values are: ``owner``, ``writer``, ``reader`` :param bool notify: Whether to send an email to the target user/domain. Default ``True``. :param str email_message: (optional) An email message to be sent if ``notify=True``. :param bool with_link: Whether the link is required for this permission to be active. Default ``False``. :returns dict: the newly created permission Examples:: # Give write permissions to otto@example.com gc.insert_permission( '0BmgG6nO_6dprnRRUWl1UFE', 'otto@example.org', perm_type='user', role='writer' ) # Make the spreadsheet publicly readable gc.insert_permission( '0BmgG6nO_6dprnRRUWl1UFE', None, perm_type='anyone', role='reader' ) """ url = "{}/{}/permissions".format(DRIVE_FILES_API_V3_URL, file_id) payload = { "type": perm_type, "role": role, "withLink": with_link, } params: ParamsType = { "supportsAllDrives": "true", } if perm_type == "domain": payload["domain"] = email_address elif perm_type in {"user", "group"}: payload["emailAddress"] = email_address params["sendNotificationEmail"] = notify params["emailMessage"] = email_message elif perm_type == "anyone": pass else: raise ValueError("Invalid permission type: {}".format(perm_type)) return self.request("post", url, json=payload, params=params)
(self, file_id: str, email_address: Optional[str], perm_type: Optional[str], role: Optional[str], notify: bool = True, email_message: Optional[str] = None, with_link: bool = False) -> requests.models.Response
708,112
gspread.http_client
list_permissions
Retrieve a list of permissions for a file. :param str file_id: a spreadsheet ID (aka file ID).
def list_permissions(self, file_id: str) -> List[Dict[str, Union[str, bool]]]: """Retrieve a list of permissions for a file. :param str file_id: a spreadsheet ID (aka file ID). """ url = "{}/{}/permissions".format(DRIVE_FILES_API_V3_URL, file_id) params: ParamsType = { "supportsAllDrives": True, "fields": "nextPageToken,permissions", } token = "" permissions = [] while token is not None: if token: params["pageToken"] = token r = self.request("get", url, params=params).json() permissions.extend(r["permissions"]) token = r.get("nextPageToken", None) return permissions
(self, file_id: str) -> List[Dict[str, Union[str, bool]]]
708,113
gspread.http_client
login
null
def login(self) -> None: from google.auth.transport.requests import Request self.auth.refresh(Request(self.session)) self.session.headers.update({"Authorization": "Bearer %s" % self.auth.token})
(self) -> NoneType
708,114
gspread.http_client
remove_permission
Deletes a permission from a file. :param str file_id: a spreadsheet ID (aka file ID.) :param str permission_id: an ID for the permission.
def remove_permission(self, file_id: str, permission_id: str) -> None: """Deletes a permission from a file. :param str file_id: a spreadsheet ID (aka file ID.) :param str permission_id: an ID for the permission. """ url = "{}/{}/permissions/{}".format( DRIVE_FILES_API_V3_URL, file_id, permission_id ) params: ParamsType = {"supportsAllDrives": True} self.request("delete", url, params=params)
(self, file_id: str, permission_id: str) -> NoneType
708,115
gspread.http_client
request
null
def request(self, *args: Any, **kwargs: Any) -> Response: # Check if we should retry the request def _should_retry( code: int, error: Mapping[str, Any], wait: int, ) -> bool: # Drive API return a dict object 'errors', the sheet API does not if "errors" in error: # Drive API returns a code 403 when reaching quotas/usage limits if ( code == HTTPStatus.FORBIDDEN and error["errors"][0]["domain"] == "usageLimits" ): return True # We retry if: # - the return code is one of: # - 429: too many requests # - 408: request timeout # - >= 500: some server error # - AND we did not reach the max retry limit return ( code in self._HTTP_ERROR_CODES or code >= HTTPStatus.INTERNAL_SERVER_ERROR ) and wait <= self._MAX_BACKOFF try: return super().request(*args, **kwargs) except APIError as err: code = err.code error = err.error self._NR_BACKOFF += 1 wait = min(2**self._NR_BACKOFF, self._MAX_BACKOFF) # check if error should retry if _should_retry(code, error, wait) is True: time.sleep(wait) # make the request again response = self.request(*args, **kwargs) # reset counters for next time self._NR_BACKOFF = 0 return response # failed too many times, raise APIEerror raise err
(self, *args: Any, **kwargs: Any) -> requests.models.Response
708,116
gspread.http_client
set_timeout
How long to wait for the server to send data before giving up, as a float, or a ``(connect timeout, read timeout)`` tuple. Use value ``None`` to restore default timeout Value for ``timeout`` is in seconds (s).
def set_timeout(self, timeout: Optional[Union[float, Tuple[float, float]]]) -> None: """How long to wait for the server to send data before giving up, as a float, or a ``(connect timeout, read timeout)`` tuple. Use value ``None`` to restore default timeout Value for ``timeout`` is in seconds (s). """ self.timeout = timeout
(self, timeout: Union[float, Tuple[float, float], NoneType]) -> NoneType
708,117
gspread.http_client
spreadsheets_get
A method stub that directly calls `spreadsheets.get <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/get>`_.
def spreadsheets_get(self, id: str, params: Optional[ParamsType] = None) -> Any: """A method stub that directly calls `spreadsheets.get <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/get>`_.""" url = SPREADSHEET_URL % id r = self.request("get", url, params=params) return r.json()
(self, id: str, params: Optional[MutableMapping[str, Union[str, int, bool, float, List[str], NoneType]]] = None) -> Any
708,118
gspread.http_client
spreadsheets_sheets_copy_to
Lower-level method that directly calls `spreadsheets.sheets.copyTo <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.sheets/copyTo>`_.
def spreadsheets_sheets_copy_to( self, id: str, sheet_id: int, destination_spreadsheet_id: str ) -> Any: """Lower-level method that directly calls `spreadsheets.sheets.copyTo <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.sheets/copyTo>`_.""" url = SPREADSHEET_SHEETS_COPY_TO_URL % (id, sheet_id) body = {"destinationSpreadsheetId": destination_spreadsheet_id} r = self.request("post", url, json=body) return r.json()
(self, id: str, sheet_id: int, destination_spreadsheet_id: str) -> Any
708,119
gspread.http_client
values_append
Lower-level method that directly calls `spreadsheets/<ID>/values:append <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of a range to search for a logical table of data. Values will be appended after the last row of the table. :param dict params: `Values Append Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#query-parameters>`_. :param dict body: `Values Append Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#request-body>`_. :returns: `Values Append Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#response-body>`_. :rtype: dict .. versionadded:: 3.0
def values_append( self, id: str, range: str, params: ParamsType, body: Optional[Mapping[str, Any]] ) -> Any: """Lower-level method that directly calls `spreadsheets/<ID>/values:append <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of a range to search for a logical table of data. Values will be appended after the last row of the table. :param dict params: `Values Append Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#query-parameters>`_. :param dict body: `Values Append Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#request-body>`_. :returns: `Values Append Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#response-body>`_. :rtype: dict .. versionadded:: 3.0 """ url = SPREADSHEET_VALUES_APPEND_URL % (id, quote(range)) r = self.request("post", url, params=params, json=body) return r.json()
(self, id: str, range: str, params: MutableMapping[str, Union[str, int, bool, float, List[str], NoneType]], body: Optional[Mapping[str, Any]]) -> Any
708,120
gspread.http_client
values_batch_clear
Lower-level method that directly calls `spreadsheets/<ID>/values:batchClear` :param dict params: (optional) `Values Batch Clear Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchClear#path-parameters>`_. :param dict body: (optional) `Values Batch Clear request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchClear#request-body>`_. :rtype: dict
def values_batch_clear( self, id: str, params: Optional[ParamsType] = None, body: Optional[Mapping[str, Any]] = None, ) -> Any: """Lower-level method that directly calls `spreadsheets/<ID>/values:batchClear` :param dict params: (optional) `Values Batch Clear Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchClear#path-parameters>`_. :param dict body: (optional) `Values Batch Clear request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchClear#request-body>`_. :rtype: dict """ url = SPREADSHEET_VALUES_BATCH_CLEAR_URL % id r = self.request("post", url, params=params, json=body) return r.json()
(self, id: str, params: Optional[MutableMapping[str, Union[str, int, bool, float, List[str], NoneType]]] = None, body: Optional[Mapping[str, Any]] = None) -> Any
708,121
gspread.http_client
values_batch_get
Lower-level method that directly calls `spreadsheets/<ID>/values:batchGet <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchGet>`_. :param list ranges: List of ranges in the `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to retrieve. :param dict params: (optional) `Values Batch Get Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchGet#query-parameters>`_. :returns: `Values Batch Get Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchGet#response-body>`_. :rtype: dict
def values_batch_get( self, id: str, ranges: List[str], params: Optional[ParamsType] = None ) -> Any: """Lower-level method that directly calls `spreadsheets/<ID>/values:batchGet <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchGet>`_. :param list ranges: List of ranges in the `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to retrieve. :param dict params: (optional) `Values Batch Get Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchGet#query-parameters>`_. :returns: `Values Batch Get Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchGet#response-body>`_. :rtype: dict """ if params is None: params = {} params["ranges"] = ranges url = SPREADSHEET_VALUES_BATCH_URL % id r = self.request("get", url, params=params) return r.json()
(self, id: str, ranges: List[str], params: Optional[MutableMapping[str, Union[str, int, bool, float, List[str], NoneType]]] = None) -> Any
708,122
gspread.http_client
values_batch_update
Lower-level method that directly calls `spreadsheets/<ID>/values:batchUpdate <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdate>`_. :param dict body: (optional) `Values Batch Update Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdate#request-body>`_. :returns: `Values Batch Update Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdate#response-body>`_. :rtype: dict
def values_batch_update( self, id: str, body: Optional[Mapping[str, Any]] = None ) -> Any: """Lower-level method that directly calls `spreadsheets/<ID>/values:batchUpdate <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdate>`_. :param dict body: (optional) `Values Batch Update Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdate#request-body>`_. :returns: `Values Batch Update Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdate#response-body>`_. :rtype: dict """ url = SPREADSHEET_VALUES_BATCH_UPDATE_URL % id r = self.request("post", url, json=body) return r.json()
(self, id: str, body: Optional[Mapping[str, Any]] = None) -> Any
708,123
gspread.http_client
values_clear
Lower-level method that directly calls `spreadsheets/<ID>/values:clear <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/clear>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to clear. :returns: `Values Clear Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/clear#response-body>`_. :rtype: dict .. versionadded:: 3.0
def values_clear(self, id: str, range: str) -> Any: """Lower-level method that directly calls `spreadsheets/<ID>/values:clear <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/clear>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to clear. :returns: `Values Clear Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/clear#response-body>`_. :rtype: dict .. versionadded:: 3.0 """ url = SPREADSHEET_VALUES_CLEAR_URL % (id, quote(range)) r = self.request("post", url) return r.json()
(self, id: str, range: str) -> Any
708,124
gspread.http_client
values_get
Lower-level method that directly calls `GET spreadsheets/<ID>/values/<range> <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to retrieve. :param dict params: (optional) `Values Get Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get#query-parameters>`_. :returns: `Values Get Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get#response-body>`_. :rtype: dict .. versionadded:: 3.0
def values_get( self, id: str, range: str, params: Optional[ParamsType] = None ) -> Any: """Lower-level method that directly calls `GET spreadsheets/<ID>/values/<range> <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to retrieve. :param dict params: (optional) `Values Get Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get#query-parameters>`_. :returns: `Values Get Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get#response-body>`_. :rtype: dict .. versionadded:: 3.0 """ url = SPREADSHEET_VALUES_URL % (id, quote(range)) r = self.request("get", url, params=params) return r.json()
(self, id: str, range: str, params: Optional[MutableMapping[str, Union[str, int, bool, float, List[str], NoneType]]] = None) -> Any
708,125
gspread.http_client
values_update
Lower-level method that directly calls `PUT spreadsheets/<ID>/values/<range> <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to update. :param dict params: (optional) `Values Update Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update#query-parameters>`_. :param dict body: (optional) `Values Update Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update#request-body>`_. :returns: `Values Update Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update#response-body>`_. :rtype: dict Example:: sh.values_update( 'Sheet1!A2', params={ 'valueInputOption': 'USER_ENTERED' }, body={ 'values': [[1, 2, 3]] } ) .. versionadded:: 3.0
def values_update( self, id: str, range: str, params: Optional[ParamsType] = None, body: Optional[Mapping[str, Any]] = None, ) -> Any: """Lower-level method that directly calls `PUT spreadsheets/<ID>/values/<range> <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to update. :param dict params: (optional) `Values Update Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update#query-parameters>`_. :param dict body: (optional) `Values Update Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update#request-body>`_. :returns: `Values Update Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update#response-body>`_. :rtype: dict Example:: sh.values_update( 'Sheet1!A2', params={ 'valueInputOption': 'USER_ENTERED' }, body={ 'values': [[1, 2, 3]] } ) .. versionadded:: 3.0 """ url = SPREADSHEET_VALUES_URL % (id, quote(range)) r = self.request("put", url, params=params, json=body) return r.json()
(self, id: str, range: str, params: Optional[MutableMapping[str, Union[str, int, bool, float, List[str], NoneType]]] = None, body: Optional[Mapping[str, Any]] = None) -> Any
708,130
gspread.client
Client
An instance of this class Manages Spreadsheet files It is used to: - open/create/list/delete spreadsheets - create/delete/list spreadsheet permission - etc It is the gspread entry point. It will handle creating necessary :class:`~gspread.models.Spreadsheet` instances.
class Client: """An instance of this class Manages Spreadsheet files It is used to: - open/create/list/delete spreadsheets - create/delete/list spreadsheet permission - etc It is the gspread entry point. It will handle creating necessary :class:`~gspread.models.Spreadsheet` instances. """ def __init__( self, auth: Credentials, session: Optional[Session] = None, http_client: HTTPClientType = HTTPClient, ) -> None: self.http_client = http_client(auth, session) def set_timeout(self, timeout: Optional[Union[float, Tuple[float, float]]] = None): """How long to wait for the server to send data before giving up, as a float, or a ``(connect timeout, read timeout)`` tuple. Use value ``None`` to restore default timeout Value for ``timeout`` is in seconds (s). """ self.http_client.set_timeout(timeout) def get_file_drive_metadata(self, id: str) -> Any: """Get the metadata from the Drive API for a specific file This method is mainly here to retrieve the create/update time of a file (these metadata are only accessible from the Drive API). """ return self.http_client.get_file_drive_metadata(id) def list_spreadsheet_files( self, title: Optional[str] = None, folder_id: Optional[str] = None ) -> List[Dict[str, Any]]: """List all the spreadsheet files Will list all spreadsheet files owned by/shared with this user account. :param str title: Filter only spreadsheet files with this title :param str folder_id: Only look for spreadsheet files in this folder The parameter ``folder_id`` can be obtained from the URL when looking at a folder in a web browser as follow: ``https://drive.google.com/drive/u/0/folders/<folder_id>`` :returns: a list of dicts containing the keys id, name, createdTime and modifiedTime. """ files, _ = self._list_spreadsheet_files(title=title, folder_id=folder_id) return files def _list_spreadsheet_files( self, title=None, folder_id=None ) -> Tuple[List[Dict[str, Any]], Response]: files = [] page_token = "" url = DRIVE_FILES_API_V3_URL query = f'mimeType="{MimeType.google_sheets}"' if title: query += f' and name = "{title}"' if folder_id: query += f' and parents in "{folder_id}"' params: ParamsType = { "q": query, "pageSize": 1000, "supportsAllDrives": True, "includeItemsFromAllDrives": True, "fields": "kind,nextPageToken,files(id,name,createdTime,modifiedTime)", } while True: if page_token: params["pageToken"] = page_token response = self.http_client.request("get", url, params=params) response_json = response.json() files.extend(response_json["files"]) page_token = response_json.get("nextPageToken", None) if page_token is None: break return files, response def open(self, title: str, folder_id: Optional[str] = None) -> Spreadsheet: """Opens a spreadsheet. :param str title: A title of a spreadsheet. :param str folder_id: (optional) If specified can be used to filter spreadsheets by parent folder ID. :returns: a :class:`~gspread.models.Spreadsheet` instance. If there's more than one spreadsheet with same title the first one will be opened. :raises gspread.SpreadsheetNotFound: if no spreadsheet with specified `title` is found. >>> gc.open('My fancy spreadsheet') """ spreadsheet_files, response = self._list_spreadsheet_files(title, folder_id) try: properties = finditem( lambda x: x["name"] == title, spreadsheet_files, ) except StopIteration as ex: raise SpreadsheetNotFound(response) from ex # Drive uses different terminology properties["title"] = properties["name"] return Spreadsheet(self.http_client, properties) def open_by_key(self, key: str) -> Spreadsheet: """Opens a spreadsheet specified by `key` (a.k.a Spreadsheet ID). :param str key: A key of a spreadsheet as it appears in a URL in a browser. :returns: a :class:`~gspread.models.Spreadsheet` instance. >>> gc.open_by_key('0BmgG6nO_6dprdS1MN3d3MkdPa142WFRrdnRRUWl1UFE') """ try: spreadsheet = Spreadsheet(self.http_client, {"id": key}) except APIError as ex: if ex.response.status_code == HTTPStatus.NOT_FOUND: raise SpreadsheetNotFound(ex.response) from ex if ex.response.status_code == HTTPStatus.FORBIDDEN: raise PermissionError from ex raise ex return spreadsheet def open_by_url(self, url: str) -> Spreadsheet: """Opens a spreadsheet specified by `url`. :param str url: URL of a spreadsheet as it appears in a browser. :returns: a :class:`~gspread.models.Spreadsheet` instance. :raises gspread.SpreadsheetNotFound: if no spreadsheet with specified `url` is found. >>> gc.open_by_url('https://docs.google.com/spreadsheet/ccc?key=0Bm...FE&hl') """ return self.open_by_key(extract_id_from_url(url)) def openall(self, title: Optional[str] = None) -> List[Spreadsheet]: """Opens all available spreadsheets. :param str title: (optional) If specified can be used to filter spreadsheets by title. :returns: a list of :class:`~gspread.models.Spreadsheet` instances. """ spreadsheet_files = self.list_spreadsheet_files(title) if title: spreadsheet_files = [ spread for spread in spreadsheet_files if title == spread["name"] ] return [ Spreadsheet(self.http_client, dict(title=x["name"], **x)) for x in spreadsheet_files ] def create(self, title: str, folder_id: Optional[str] = None) -> Spreadsheet: """Creates a new spreadsheet. :param str title: A title of a new spreadsheet. :param str folder_id: Id of the folder where we want to save the spreadsheet. :returns: a :class:`~gspread.models.Spreadsheet` instance. """ payload: Dict[str, Any] = { "name": title, "mimeType": MimeType.google_sheets, } params: ParamsType = { "supportsAllDrives": True, } if folder_id is not None: payload["parents"] = [folder_id] r = self.http_client.request( "post", DRIVE_FILES_API_V3_URL, json=payload, params=params ) spreadsheet_id = r.json()["id"] return self.open_by_key(spreadsheet_id) def export(self, file_id: str, format: str = ExportFormat.PDF) -> bytes: """Export the spreadsheet in the given format. :param str file_id: The key of the spreadsheet to export :param str format: The format of the resulting file. Possible values are: * ``ExportFormat.PDF`` * ``ExportFormat.EXCEL`` * ``ExportFormat.CSV`` * ``ExportFormat.OPEN_OFFICE_SHEET`` * ``ExportFormat.TSV`` * ``ExportFormat.ZIPPED_HTML`` See `ExportFormat`_ in the Drive API. :type format: :class:`~gspread.utils.ExportFormat` :returns bytes: The content of the exported file. .. _ExportFormat: https://developers.google.com/drive/api/guides/ref-export-formats """ return self.http_client.export(file_id=file_id, format=format) def copy( self, file_id: str, title: Optional[str] = None, copy_permissions: bool = False, folder_id: Optional[str] = None, copy_comments: bool = True, ) -> Spreadsheet: """Copies a spreadsheet. :param str file_id: A key of a spreadsheet to copy. :param str title: (optional) A title for the new spreadsheet. :param bool copy_permissions: (optional) If True, copy permissions from the original spreadsheet to the new spreadsheet. :param str folder_id: Id of the folder where we want to save the spreadsheet. :param bool copy_comments: (optional) If True, copy the comments from the original spreadsheet to the new spreadsheet. :returns: a :class:`~gspread.models.Spreadsheet` instance. .. versionadded:: 3.1.0 .. note:: If you're using custom credentials without the Drive scope, you need to add ``https://www.googleapis.com/auth/drive`` to your OAuth scope in order to use this method. Example:: scope = [ 'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive' ] Otherwise, you will get an ``Insufficient Permission`` error when you try to copy a spreadsheet. """ url = "{}/{}/copy".format(DRIVE_FILES_API_V3_URL, file_id) payload: Dict[str, Any] = { "name": title, "mimeType": MimeType.google_sheets, } if folder_id is not None: payload["parents"] = [folder_id] params: ParamsType = {"supportsAllDrives": True} r = self.http_client.request("post", url, json=payload, params=params) spreadsheet_id = r.json()["id"] new_spreadsheet = self.open_by_key(spreadsheet_id) if copy_permissions is True: original = self.open_by_key(file_id) permissions = original.list_permissions() for p in permissions: if p.get("deleted"): continue new_spreadsheet.share( email_address=p["emailAddress"], perm_type=p["type"], role=p["role"], notify=False, ) if copy_comments is True: source_url = DRIVE_FILES_API_V3_COMMENTS_URL % (file_id) page_token = "" comments = [] params = { "fields": "comments/content,comments/anchor,nextPageToken", "includeDeleted": False, "pageSize": 100, # API limit to maximum 100 } while page_token is not None: params["pageToken"] = page_token res = self.http_client.request("get", source_url, params=params).json() comments.extend(res["comments"]) page_token = res.get("nextPageToken", None) destination_url = DRIVE_FILES_API_V3_COMMENTS_URL % (new_spreadsheet.id) # requesting some fields in the response is mandatory from the API. # choose 'id' randomly out of all the fields, but no need to use it for now. params = {"fields": "id"} for comment in comments: self.http_client.request( "post", destination_url, json=comment, params=params ) return new_spreadsheet def del_spreadsheet(self, file_id: str) -> None: """Deletes a spreadsheet. :param str file_id: a spreadsheet ID (a.k.a file ID). """ url = "{}/{}".format(DRIVE_FILES_API_V3_URL, file_id) params: ParamsType = {"supportsAllDrives": True} self.http_client.request("delete", url, params=params) def import_csv(self, file_id: str, data: Union[str, bytes]) -> Any: """Imports data into the first page of the spreadsheet. :param str file_id: :param str data: A CSV string of data. Example: .. code:: # Read CSV file contents content = open('file_to_import.csv', 'r').read() gc.import_csv(spreadsheet.id, content) .. note:: This method removes all other worksheets and then entirely replaces the contents of the first worksheet. """ return self.http_client.import_csv(file_id, data) def list_permissions(self, file_id: str) -> List[Dict[str, Union[str, bool]]]: """Retrieve a list of permissions for a file. :param str file_id: a spreadsheet ID (aka file ID). """ return self.http_client.list_permissions(file_id) def insert_permission( self, file_id: str, value: Optional[str] = None, perm_type: Optional[str] = None, role: Optional[str] = None, notify: bool = True, email_message: Optional[str] = None, with_link: bool = False, ) -> Response: """Creates a new permission for a file. :param str file_id: a spreadsheet ID (aka file ID). :param value: user or group e-mail address, domain name or None for 'anyone' type. :type value: str, None :param str perm_type: (optional) The account type. Allowed values are: ``user``, ``group``, ``domain``, ``anyone`` :param str role: (optional) The primary role for this user. Allowed values are: ``owner``, ``writer``, ``reader`` :param bool notify: (optional) Whether to send an email to the target user/domain. :param str email_message: (optional) An email message to be sent if ``notify=True``. :param bool with_link: (optional) Whether the link is required for this permission to be active. :returns dict: the newly created permission Examples:: # Give write permissions to otto@example.com gc.insert_permission( '0BmgG6nO_6dprnRRUWl1UFE', 'otto@example.org', perm_type='user', role='writer' ) # Make the spreadsheet publicly readable gc.insert_permission( '0BmgG6nO_6dprnRRUWl1UFE', None, perm_type='anyone', role='reader' ) """ return self.http_client.insert_permission( file_id, value, perm_type, role, notify, email_message, with_link ) def remove_permission(self, file_id: str, permission_id: str) -> None: """Deletes a permission from a file. :param str file_id: a spreadsheet ID (aka file ID.) :param str permission_id: an ID for the permission. """ self.http_client.remove_permission(file_id, permission_id)
(auth: google.auth.credentials.Credentials, session: Optional[requests.sessions.Session] = None, http_client: Type[gspread.http_client.HTTPClient] = <class 'gspread.http_client.HTTPClient'>) -> None
708,131
gspread.client
__init__
null
def __init__( self, auth: Credentials, session: Optional[Session] = None, http_client: HTTPClientType = HTTPClient, ) -> None: self.http_client = http_client(auth, session)
(self, auth: google.auth.credentials.Credentials, session: Optional[requests.sessions.Session] = None, http_client: Type[gspread.http_client.HTTPClient] = <class 'gspread.http_client.HTTPClient'>) -> NoneType
708,132
gspread.client
_list_spreadsheet_files
null
def _list_spreadsheet_files( self, title=None, folder_id=None ) -> Tuple[List[Dict[str, Any]], Response]: files = [] page_token = "" url = DRIVE_FILES_API_V3_URL query = f'mimeType="{MimeType.google_sheets}"' if title: query += f' and name = "{title}"' if folder_id: query += f' and parents in "{folder_id}"' params: ParamsType = { "q": query, "pageSize": 1000, "supportsAllDrives": True, "includeItemsFromAllDrives": True, "fields": "kind,nextPageToken,files(id,name,createdTime,modifiedTime)", } while True: if page_token: params["pageToken"] = page_token response = self.http_client.request("get", url, params=params) response_json = response.json() files.extend(response_json["files"]) page_token = response_json.get("nextPageToken", None) if page_token is None: break return files, response
(self, title=None, folder_id=None) -> Tuple[List[Dict[str, Any]], requests.models.Response]
708,133
gspread.client
copy
Copies a spreadsheet. :param str file_id: A key of a spreadsheet to copy. :param str title: (optional) A title for the new spreadsheet. :param bool copy_permissions: (optional) If True, copy permissions from the original spreadsheet to the new spreadsheet. :param str folder_id: Id of the folder where we want to save the spreadsheet. :param bool copy_comments: (optional) If True, copy the comments from the original spreadsheet to the new spreadsheet. :returns: a :class:`~gspread.models.Spreadsheet` instance. .. versionadded:: 3.1.0 .. note:: If you're using custom credentials without the Drive scope, you need to add ``https://www.googleapis.com/auth/drive`` to your OAuth scope in order to use this method. Example:: scope = [ 'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive' ] Otherwise, you will get an ``Insufficient Permission`` error when you try to copy a spreadsheet.
def copy( self, file_id: str, title: Optional[str] = None, copy_permissions: bool = False, folder_id: Optional[str] = None, copy_comments: bool = True, ) -> Spreadsheet: """Copies a spreadsheet. :param str file_id: A key of a spreadsheet to copy. :param str title: (optional) A title for the new spreadsheet. :param bool copy_permissions: (optional) If True, copy permissions from the original spreadsheet to the new spreadsheet. :param str folder_id: Id of the folder where we want to save the spreadsheet. :param bool copy_comments: (optional) If True, copy the comments from the original spreadsheet to the new spreadsheet. :returns: a :class:`~gspread.models.Spreadsheet` instance. .. versionadded:: 3.1.0 .. note:: If you're using custom credentials without the Drive scope, you need to add ``https://www.googleapis.com/auth/drive`` to your OAuth scope in order to use this method. Example:: scope = [ 'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive' ] Otherwise, you will get an ``Insufficient Permission`` error when you try to copy a spreadsheet. """ url = "{}/{}/copy".format(DRIVE_FILES_API_V3_URL, file_id) payload: Dict[str, Any] = { "name": title, "mimeType": MimeType.google_sheets, } if folder_id is not None: payload["parents"] = [folder_id] params: ParamsType = {"supportsAllDrives": True} r = self.http_client.request("post", url, json=payload, params=params) spreadsheet_id = r.json()["id"] new_spreadsheet = self.open_by_key(spreadsheet_id) if copy_permissions is True: original = self.open_by_key(file_id) permissions = original.list_permissions() for p in permissions: if p.get("deleted"): continue new_spreadsheet.share( email_address=p["emailAddress"], perm_type=p["type"], role=p["role"], notify=False, ) if copy_comments is True: source_url = DRIVE_FILES_API_V3_COMMENTS_URL % (file_id) page_token = "" comments = [] params = { "fields": "comments/content,comments/anchor,nextPageToken", "includeDeleted": False, "pageSize": 100, # API limit to maximum 100 } while page_token is not None: params["pageToken"] = page_token res = self.http_client.request("get", source_url, params=params).json() comments.extend(res["comments"]) page_token = res.get("nextPageToken", None) destination_url = DRIVE_FILES_API_V3_COMMENTS_URL % (new_spreadsheet.id) # requesting some fields in the response is mandatory from the API. # choose 'id' randomly out of all the fields, but no need to use it for now. params = {"fields": "id"} for comment in comments: self.http_client.request( "post", destination_url, json=comment, params=params ) return new_spreadsheet
(self, file_id: str, title: Optional[str] = None, copy_permissions: bool = False, folder_id: Optional[str] = None, copy_comments: bool = True) -> gspread.spreadsheet.Spreadsheet
708,134
gspread.client
create
Creates a new spreadsheet. :param str title: A title of a new spreadsheet. :param str folder_id: Id of the folder where we want to save the spreadsheet. :returns: a :class:`~gspread.models.Spreadsheet` instance.
def create(self, title: str, folder_id: Optional[str] = None) -> Spreadsheet: """Creates a new spreadsheet. :param str title: A title of a new spreadsheet. :param str folder_id: Id of the folder where we want to save the spreadsheet. :returns: a :class:`~gspread.models.Spreadsheet` instance. """ payload: Dict[str, Any] = { "name": title, "mimeType": MimeType.google_sheets, } params: ParamsType = { "supportsAllDrives": True, } if folder_id is not None: payload["parents"] = [folder_id] r = self.http_client.request( "post", DRIVE_FILES_API_V3_URL, json=payload, params=params ) spreadsheet_id = r.json()["id"] return self.open_by_key(spreadsheet_id)
(self, title: str, folder_id: Optional[str] = None) -> gspread.spreadsheet.Spreadsheet
708,135
gspread.client
del_spreadsheet
Deletes a spreadsheet. :param str file_id: a spreadsheet ID (a.k.a file ID).
def del_spreadsheet(self, file_id: str) -> None: """Deletes a spreadsheet. :param str file_id: a spreadsheet ID (a.k.a file ID). """ url = "{}/{}".format(DRIVE_FILES_API_V3_URL, file_id) params: ParamsType = {"supportsAllDrives": True} self.http_client.request("delete", url, params=params)
(self, file_id: str) -> NoneType
708,136
gspread.client
export
Export the spreadsheet in the given format. :param str file_id: The key of the spreadsheet to export :param str format: The format of the resulting file. Possible values are: * ``ExportFormat.PDF`` * ``ExportFormat.EXCEL`` * ``ExportFormat.CSV`` * ``ExportFormat.OPEN_OFFICE_SHEET`` * ``ExportFormat.TSV`` * ``ExportFormat.ZIPPED_HTML`` See `ExportFormat`_ in the Drive API. :type format: :class:`~gspread.utils.ExportFormat` :returns bytes: The content of the exported file. .. _ExportFormat: https://developers.google.com/drive/api/guides/ref-export-formats
def export(self, file_id: str, format: str = ExportFormat.PDF) -> bytes: """Export the spreadsheet in the given format. :param str file_id: The key of the spreadsheet to export :param str format: The format of the resulting file. Possible values are: * ``ExportFormat.PDF`` * ``ExportFormat.EXCEL`` * ``ExportFormat.CSV`` * ``ExportFormat.OPEN_OFFICE_SHEET`` * ``ExportFormat.TSV`` * ``ExportFormat.ZIPPED_HTML`` See `ExportFormat`_ in the Drive API. :type format: :class:`~gspread.utils.ExportFormat` :returns bytes: The content of the exported file. .. _ExportFormat: https://developers.google.com/drive/api/guides/ref-export-formats """ return self.http_client.export(file_id=file_id, format=format)
(self, file_id: str, format: str = <ExportFormat.PDF: 'application/pdf'>) -> bytes
708,137
gspread.client
get_file_drive_metadata
Get the metadata from the Drive API for a specific file This method is mainly here to retrieve the create/update time of a file (these metadata are only accessible from the Drive API).
def get_file_drive_metadata(self, id: str) -> Any: """Get the metadata from the Drive API for a specific file This method is mainly here to retrieve the create/update time of a file (these metadata are only accessible from the Drive API). """ return self.http_client.get_file_drive_metadata(id)
(self, id: str) -> Any
708,138
gspread.client
import_csv
Imports data into the first page of the spreadsheet. :param str file_id: :param str data: A CSV string of data. Example: .. code:: # Read CSV file contents content = open('file_to_import.csv', 'r').read() gc.import_csv(spreadsheet.id, content) .. note:: This method removes all other worksheets and then entirely replaces the contents of the first worksheet.
def import_csv(self, file_id: str, data: Union[str, bytes]) -> Any: """Imports data into the first page of the spreadsheet. :param str file_id: :param str data: A CSV string of data. Example: .. code:: # Read CSV file contents content = open('file_to_import.csv', 'r').read() gc.import_csv(spreadsheet.id, content) .. note:: This method removes all other worksheets and then entirely replaces the contents of the first worksheet. """ return self.http_client.import_csv(file_id, data)
(self, file_id: str, data: Union[str, bytes]) -> Any
708,139
gspread.client
insert_permission
Creates a new permission for a file. :param str file_id: a spreadsheet ID (aka file ID). :param value: user or group e-mail address, domain name or None for 'anyone' type. :type value: str, None :param str perm_type: (optional) The account type. Allowed values are: ``user``, ``group``, ``domain``, ``anyone`` :param str role: (optional) The primary role for this user. Allowed values are: ``owner``, ``writer``, ``reader`` :param bool notify: (optional) Whether to send an email to the target user/domain. :param str email_message: (optional) An email message to be sent if ``notify=True``. :param bool with_link: (optional) Whether the link is required for this permission to be active. :returns dict: the newly created permission Examples:: # Give write permissions to otto@example.com gc.insert_permission( '0BmgG6nO_6dprnRRUWl1UFE', 'otto@example.org', perm_type='user', role='writer' ) # Make the spreadsheet publicly readable gc.insert_permission( '0BmgG6nO_6dprnRRUWl1UFE', None, perm_type='anyone', role='reader' )
def insert_permission( self, file_id: str, value: Optional[str] = None, perm_type: Optional[str] = None, role: Optional[str] = None, notify: bool = True, email_message: Optional[str] = None, with_link: bool = False, ) -> Response: """Creates a new permission for a file. :param str file_id: a spreadsheet ID (aka file ID). :param value: user or group e-mail address, domain name or None for 'anyone' type. :type value: str, None :param str perm_type: (optional) The account type. Allowed values are: ``user``, ``group``, ``domain``, ``anyone`` :param str role: (optional) The primary role for this user. Allowed values are: ``owner``, ``writer``, ``reader`` :param bool notify: (optional) Whether to send an email to the target user/domain. :param str email_message: (optional) An email message to be sent if ``notify=True``. :param bool with_link: (optional) Whether the link is required for this permission to be active. :returns dict: the newly created permission Examples:: # Give write permissions to otto@example.com gc.insert_permission( '0BmgG6nO_6dprnRRUWl1UFE', 'otto@example.org', perm_type='user', role='writer' ) # Make the spreadsheet publicly readable gc.insert_permission( '0BmgG6nO_6dprnRRUWl1UFE', None, perm_type='anyone', role='reader' ) """ return self.http_client.insert_permission( file_id, value, perm_type, role, notify, email_message, with_link )
(self, file_id: str, value: Optional[str] = None, perm_type: Optional[str] = None, role: Optional[str] = None, notify: bool = True, email_message: Optional[str] = None, with_link: bool = False) -> requests.models.Response
708,140
gspread.client
list_permissions
Retrieve a list of permissions for a file. :param str file_id: a spreadsheet ID (aka file ID).
def list_permissions(self, file_id: str) -> List[Dict[str, Union[str, bool]]]: """Retrieve a list of permissions for a file. :param str file_id: a spreadsheet ID (aka file ID). """ return self.http_client.list_permissions(file_id)
(self, file_id: str) -> List[Dict[str, Union[str, bool]]]
708,141
gspread.client
list_spreadsheet_files
List all the spreadsheet files Will list all spreadsheet files owned by/shared with this user account. :param str title: Filter only spreadsheet files with this title :param str folder_id: Only look for spreadsheet files in this folder The parameter ``folder_id`` can be obtained from the URL when looking at a folder in a web browser as follow: ``https://drive.google.com/drive/u/0/folders/<folder_id>`` :returns: a list of dicts containing the keys id, name, createdTime and modifiedTime.
def list_spreadsheet_files( self, title: Optional[str] = None, folder_id: Optional[str] = None ) -> List[Dict[str, Any]]: """List all the spreadsheet files Will list all spreadsheet files owned by/shared with this user account. :param str title: Filter only spreadsheet files with this title :param str folder_id: Only look for spreadsheet files in this folder The parameter ``folder_id`` can be obtained from the URL when looking at a folder in a web browser as follow: ``https://drive.google.com/drive/u/0/folders/<folder_id>`` :returns: a list of dicts containing the keys id, name, createdTime and modifiedTime. """ files, _ = self._list_spreadsheet_files(title=title, folder_id=folder_id) return files
(self, title: Optional[str] = None, folder_id: Optional[str] = None) -> List[Dict[str, Any]]
708,142
gspread.client
open
Opens a spreadsheet. :param str title: A title of a spreadsheet. :param str folder_id: (optional) If specified can be used to filter spreadsheets by parent folder ID. :returns: a :class:`~gspread.models.Spreadsheet` instance. If there's more than one spreadsheet with same title the first one will be opened. :raises gspread.SpreadsheetNotFound: if no spreadsheet with specified `title` is found. >>> gc.open('My fancy spreadsheet')
def open(self, title: str, folder_id: Optional[str] = None) -> Spreadsheet: """Opens a spreadsheet. :param str title: A title of a spreadsheet. :param str folder_id: (optional) If specified can be used to filter spreadsheets by parent folder ID. :returns: a :class:`~gspread.models.Spreadsheet` instance. If there's more than one spreadsheet with same title the first one will be opened. :raises gspread.SpreadsheetNotFound: if no spreadsheet with specified `title` is found. >>> gc.open('My fancy spreadsheet') """ spreadsheet_files, response = self._list_spreadsheet_files(title, folder_id) try: properties = finditem( lambda x: x["name"] == title, spreadsheet_files, ) except StopIteration as ex: raise SpreadsheetNotFound(response) from ex # Drive uses different terminology properties["title"] = properties["name"] return Spreadsheet(self.http_client, properties)
(self, title: str, folder_id: Optional[str] = None) -> gspread.spreadsheet.Spreadsheet
708,143
gspread.client
open_by_key
Opens a spreadsheet specified by `key` (a.k.a Spreadsheet ID). :param str key: A key of a spreadsheet as it appears in a URL in a browser. :returns: a :class:`~gspread.models.Spreadsheet` instance. >>> gc.open_by_key('0BmgG6nO_6dprdS1MN3d3MkdPa142WFRrdnRRUWl1UFE')
def open_by_key(self, key: str) -> Spreadsheet: """Opens a spreadsheet specified by `key` (a.k.a Spreadsheet ID). :param str key: A key of a spreadsheet as it appears in a URL in a browser. :returns: a :class:`~gspread.models.Spreadsheet` instance. >>> gc.open_by_key('0BmgG6nO_6dprdS1MN3d3MkdPa142WFRrdnRRUWl1UFE') """ try: spreadsheet = Spreadsheet(self.http_client, {"id": key}) except APIError as ex: if ex.response.status_code == HTTPStatus.NOT_FOUND: raise SpreadsheetNotFound(ex.response) from ex if ex.response.status_code == HTTPStatus.FORBIDDEN: raise PermissionError from ex raise ex return spreadsheet
(self, key: str) -> gspread.spreadsheet.Spreadsheet
708,144
gspread.client
open_by_url
Opens a spreadsheet specified by `url`. :param str url: URL of a spreadsheet as it appears in a browser. :returns: a :class:`~gspread.models.Spreadsheet` instance. :raises gspread.SpreadsheetNotFound: if no spreadsheet with specified `url` is found. >>> gc.open_by_url('https://docs.google.com/spreadsheet/ccc?key=0Bm...FE&hl')
def open_by_url(self, url: str) -> Spreadsheet: """Opens a spreadsheet specified by `url`. :param str url: URL of a spreadsheet as it appears in a browser. :returns: a :class:`~gspread.models.Spreadsheet` instance. :raises gspread.SpreadsheetNotFound: if no spreadsheet with specified `url` is found. >>> gc.open_by_url('https://docs.google.com/spreadsheet/ccc?key=0Bm...FE&hl') """ return self.open_by_key(extract_id_from_url(url))
(self, url: str) -> gspread.spreadsheet.Spreadsheet
708,145
gspread.client
openall
Opens all available spreadsheets. :param str title: (optional) If specified can be used to filter spreadsheets by title. :returns: a list of :class:`~gspread.models.Spreadsheet` instances.
def openall(self, title: Optional[str] = None) -> List[Spreadsheet]: """Opens all available spreadsheets. :param str title: (optional) If specified can be used to filter spreadsheets by title. :returns: a list of :class:`~gspread.models.Spreadsheet` instances. """ spreadsheet_files = self.list_spreadsheet_files(title) if title: spreadsheet_files = [ spread for spread in spreadsheet_files if title == spread["name"] ] return [ Spreadsheet(self.http_client, dict(title=x["name"], **x)) for x in spreadsheet_files ]
(self, title: Optional[str] = None) -> List[gspread.spreadsheet.Spreadsheet]
708,146
gspread.client
remove_permission
Deletes a permission from a file. :param str file_id: a spreadsheet ID (aka file ID.) :param str permission_id: an ID for the permission.
def remove_permission(self, file_id: str, permission_id: str) -> None: """Deletes a permission from a file. :param str file_id: a spreadsheet ID (aka file ID.) :param str permission_id: an ID for the permission. """ self.http_client.remove_permission(file_id, permission_id)
(self, file_id: str, permission_id: str) -> NoneType
708,147
gspread.client
set_timeout
How long to wait for the server to send data before giving up, as a float, or a ``(connect timeout, read timeout)`` tuple. Use value ``None`` to restore default timeout Value for ``timeout`` is in seconds (s).
def set_timeout(self, timeout: Optional[Union[float, Tuple[float, float]]] = None): """How long to wait for the server to send data before giving up, as a float, or a ``(connect timeout, read timeout)`` tuple. Use value ``None`` to restore default timeout Value for ``timeout`` is in seconds (s). """ self.http_client.set_timeout(timeout)
(self, timeout: Union[float, Tuple[float, float], NoneType] = None)
708,148
gspread.exceptions
GSpreadException
A base class for gspread's exceptions.
class GSpreadException(Exception): """A base class for gspread's exceptions."""
null
708,149
gspread.http_client
HTTPClient
An instance of this class communicates with Google API. :param Credentials auth: An instance of google.auth.Credentials used to authenticate requests created by either: * gspread.auth.oauth() * gspread.auth.oauth_from_dict() * gspread.auth.service_account() * gspread.auth.service_account_from_dict() :param Session session: (Optional) An OAuth2 credential object. Credential objects created by `google-auth <https://github.com/googleapis/google-auth-library-python>`_. You can pass you own Session object, simply pass ``auth=None`` and ``session=my_custom_session``. This class is not intended to be created manually. It will be created by the gspread.Client class.
class HTTPClient: """An instance of this class communicates with Google API. :param Credentials auth: An instance of google.auth.Credentials used to authenticate requests created by either: * gspread.auth.oauth() * gspread.auth.oauth_from_dict() * gspread.auth.service_account() * gspread.auth.service_account_from_dict() :param Session session: (Optional) An OAuth2 credential object. Credential objects created by `google-auth <https://github.com/googleapis/google-auth-library-python>`_. You can pass you own Session object, simply pass ``auth=None`` and ``session=my_custom_session``. This class is not intended to be created manually. It will be created by the gspread.Client class. """ def __init__(self, auth: Credentials, session: Optional[Session] = None) -> None: if session is not None: self.session = session else: self.auth: Credentials = convert_credentials(auth) self.session = AuthorizedSession(self.auth) self.timeout: Optional[Union[float, Tuple[float, float]]] = None def login(self) -> None: from google.auth.transport.requests import Request self.auth.refresh(Request(self.session)) self.session.headers.update({"Authorization": "Bearer %s" % self.auth.token}) def set_timeout(self, timeout: Optional[Union[float, Tuple[float, float]]]) -> None: """How long to wait for the server to send data before giving up, as a float, or a ``(connect timeout, read timeout)`` tuple. Use value ``None`` to restore default timeout Value for ``timeout`` is in seconds (s). """ self.timeout = timeout def request( self, method: str, endpoint: str, params: Optional[ParamsType] = None, data: Optional[bytes] = None, json: Optional[Mapping[str, Any]] = None, files: FileType = None, headers: Optional[MutableMapping[str, str]] = None, ) -> Response: response = self.session.request( method=method, url=endpoint, json=json, params=params, data=data, files=files, headers=headers, timeout=self.timeout, ) if response.ok: return response else: raise APIError(response) def batch_update(self, id: str, body: Optional[Mapping[str, Any]]) -> Any: """Lower-level method that directly calls `spreadsheets/<ID>:batchUpdate <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate>`_. :param dict body: `Batch Update Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate#request-body>`_. :returns: `Batch Update Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate#response-body>`_. :rtype: dict .. versionadded:: 3.0 """ r = self.request("post", SPREADSHEET_BATCH_UPDATE_URL % id, json=body) return r.json() def values_update( self, id: str, range: str, params: Optional[ParamsType] = None, body: Optional[Mapping[str, Any]] = None, ) -> Any: """Lower-level method that directly calls `PUT spreadsheets/<ID>/values/<range> <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to update. :param dict params: (optional) `Values Update Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update#query-parameters>`_. :param dict body: (optional) `Values Update Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update#request-body>`_. :returns: `Values Update Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update#response-body>`_. :rtype: dict Example:: sh.values_update( 'Sheet1!A2', params={ 'valueInputOption': 'USER_ENTERED' }, body={ 'values': [[1, 2, 3]] } ) .. versionadded:: 3.0 """ url = SPREADSHEET_VALUES_URL % (id, quote(range)) r = self.request("put", url, params=params, json=body) return r.json() def values_append( self, id: str, range: str, params: ParamsType, body: Optional[Mapping[str, Any]] ) -> Any: """Lower-level method that directly calls `spreadsheets/<ID>/values:append <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of a range to search for a logical table of data. Values will be appended after the last row of the table. :param dict params: `Values Append Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#query-parameters>`_. :param dict body: `Values Append Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#request-body>`_. :returns: `Values Append Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#response-body>`_. :rtype: dict .. versionadded:: 3.0 """ url = SPREADSHEET_VALUES_APPEND_URL % (id, quote(range)) r = self.request("post", url, params=params, json=body) return r.json() def values_clear(self, id: str, range: str) -> Any: """Lower-level method that directly calls `spreadsheets/<ID>/values:clear <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/clear>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to clear. :returns: `Values Clear Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/clear#response-body>`_. :rtype: dict .. versionadded:: 3.0 """ url = SPREADSHEET_VALUES_CLEAR_URL % (id, quote(range)) r = self.request("post", url) return r.json() def values_batch_clear( self, id: str, params: Optional[ParamsType] = None, body: Optional[Mapping[str, Any]] = None, ) -> Any: """Lower-level method that directly calls `spreadsheets/<ID>/values:batchClear` :param dict params: (optional) `Values Batch Clear Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchClear#path-parameters>`_. :param dict body: (optional) `Values Batch Clear request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchClear#request-body>`_. :rtype: dict """ url = SPREADSHEET_VALUES_BATCH_CLEAR_URL % id r = self.request("post", url, params=params, json=body) return r.json() def values_get( self, id: str, range: str, params: Optional[ParamsType] = None ) -> Any: """Lower-level method that directly calls `GET spreadsheets/<ID>/values/<range> <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to retrieve. :param dict params: (optional) `Values Get Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get#query-parameters>`_. :returns: `Values Get Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get#response-body>`_. :rtype: dict .. versionadded:: 3.0 """ url = SPREADSHEET_VALUES_URL % (id, quote(range)) r = self.request("get", url, params=params) return r.json() def values_batch_get( self, id: str, ranges: List[str], params: Optional[ParamsType] = None ) -> Any: """Lower-level method that directly calls `spreadsheets/<ID>/values:batchGet <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchGet>`_. :param list ranges: List of ranges in the `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to retrieve. :param dict params: (optional) `Values Batch Get Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchGet#query-parameters>`_. :returns: `Values Batch Get Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchGet#response-body>`_. :rtype: dict """ if params is None: params = {} params["ranges"] = ranges url = SPREADSHEET_VALUES_BATCH_URL % id r = self.request("get", url, params=params) return r.json() def values_batch_update( self, id: str, body: Optional[Mapping[str, Any]] = None ) -> Any: """Lower-level method that directly calls `spreadsheets/<ID>/values:batchUpdate <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdate>`_. :param dict body: (optional) `Values Batch Update Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdate#request-body>`_. :returns: `Values Batch Update Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdate#response-body>`_. :rtype: dict """ url = SPREADSHEET_VALUES_BATCH_UPDATE_URL % id r = self.request("post", url, json=body) return r.json() def spreadsheets_get(self, id: str, params: Optional[ParamsType] = None) -> Any: """A method stub that directly calls `spreadsheets.get <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/get>`_.""" url = SPREADSHEET_URL % id r = self.request("get", url, params=params) return r.json() def spreadsheets_sheets_copy_to( self, id: str, sheet_id: int, destination_spreadsheet_id: str ) -> Any: """Lower-level method that directly calls `spreadsheets.sheets.copyTo <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.sheets/copyTo>`_.""" url = SPREADSHEET_SHEETS_COPY_TO_URL % (id, sheet_id) body = {"destinationSpreadsheetId": destination_spreadsheet_id} r = self.request("post", url, json=body) return r.json() def fetch_sheet_metadata(self, id: str, params: Optional[ParamsType] = None) -> Any: """Similar to :method spreadsheets_get:`gspread.http_client.spreadsheets_get`, get the spreadsheet form the API but by default **does not get the cells data**. It only retrieve the the metadata from the spreadsheet. :param str id: the spreadsheet ID key :param dict params: (optional) the HTTP params for the GET request. By default sets the parameter ``includeGridData`` to ``false``. :returns: The raw spreadsheet :rtype: dict """ if params is None: params = {"includeGridData": "false"} url = SPREADSHEET_URL % id r = self.request("get", url, params=params) return r.json() def get_file_drive_metadata(self, id: str) -> Any: """Get the metadata from the Drive API for a specific file This method is mainly here to retrieve the create/update time of a file (these metadata are only accessible from the Drive API). """ url = DRIVE_FILES_API_V3_URL + "/{}".format(id) params: ParamsType = { "supportsAllDrives": True, "includeItemsFromAllDrives": True, "fields": "id,name,createdTime,modifiedTime", } res = self.request("get", url, params=params) return res.json() def export(self, file_id: str, format: str = ExportFormat.PDF) -> bytes: """Export the spreadsheet in the given format. :param str file_id: The key of the spreadsheet to export :param str format: The format of the resulting file. Possible values are: * ``ExportFormat.PDF`` * ``ExportFormat.EXCEL`` * ``ExportFormat.CSV`` * ``ExportFormat.OPEN_OFFICE_SHEET`` * ``ExportFormat.TSV`` * ``ExportFormat.ZIPPED_HTML`` See `ExportFormat`_ in the Drive API. :type format: :class:`~gspread.utils.ExportFormat` :returns bytes: The content of the exported file. .. _ExportFormat: https://developers.google.com/drive/api/guides/ref-export-formats """ if format not in ExportFormat: raise UnSupportedExportFormat url = "{}/{}/export".format(DRIVE_FILES_API_V3_URL, file_id) params: ParamsType = {"mimeType": format} r = self.request("get", url, params=params) return r.content def insert_permission( self, file_id: str, email_address: Optional[str], perm_type: Optional[str], role: Optional[str], notify: bool = True, email_message: Optional[str] = None, with_link: bool = False, ) -> Response: """Creates a new permission for a file. :param str file_id: a spreadsheet ID (aka file ID). :param email_address: user or group e-mail address, domain name or None for 'anyone' type. :type email_address: str, None :param str perm_type: (optional) The account type. Allowed values are: ``user``, ``group``, ``domain``, ``anyone`` :param str role: (optional) The primary role for this user. Allowed values are: ``owner``, ``writer``, ``reader`` :param bool notify: Whether to send an email to the target user/domain. Default ``True``. :param str email_message: (optional) An email message to be sent if ``notify=True``. :param bool with_link: Whether the link is required for this permission to be active. Default ``False``. :returns dict: the newly created permission Examples:: # Give write permissions to otto@example.com gc.insert_permission( '0BmgG6nO_6dprnRRUWl1UFE', 'otto@example.org', perm_type='user', role='writer' ) # Make the spreadsheet publicly readable gc.insert_permission( '0BmgG6nO_6dprnRRUWl1UFE', None, perm_type='anyone', role='reader' ) """ url = "{}/{}/permissions".format(DRIVE_FILES_API_V3_URL, file_id) payload = { "type": perm_type, "role": role, "withLink": with_link, } params: ParamsType = { "supportsAllDrives": "true", } if perm_type == "domain": payload["domain"] = email_address elif perm_type in {"user", "group"}: payload["emailAddress"] = email_address params["sendNotificationEmail"] = notify params["emailMessage"] = email_message elif perm_type == "anyone": pass else: raise ValueError("Invalid permission type: {}".format(perm_type)) return self.request("post", url, json=payload, params=params) def list_permissions(self, file_id: str) -> List[Dict[str, Union[str, bool]]]: """Retrieve a list of permissions for a file. :param str file_id: a spreadsheet ID (aka file ID). """ url = "{}/{}/permissions".format(DRIVE_FILES_API_V3_URL, file_id) params: ParamsType = { "supportsAllDrives": True, "fields": "nextPageToken,permissions", } token = "" permissions = [] while token is not None: if token: params["pageToken"] = token r = self.request("get", url, params=params).json() permissions.extend(r["permissions"]) token = r.get("nextPageToken", None) return permissions def remove_permission(self, file_id: str, permission_id: str) -> None: """Deletes a permission from a file. :param str file_id: a spreadsheet ID (aka file ID.) :param str permission_id: an ID for the permission. """ url = "{}/{}/permissions/{}".format( DRIVE_FILES_API_V3_URL, file_id, permission_id ) params: ParamsType = {"supportsAllDrives": True} self.request("delete", url, params=params) def import_csv(self, file_id: str, data: Union[str, bytes]) -> Any: """Imports data into the first page of the spreadsheet. :param str data: A CSV string of data. Example: .. code:: # Read CSV file contents content = open('file_to_import.csv', 'r').read() gc.import_csv(spreadsheet.id, content) .. note:: This method removes all other worksheets and then entirely replaces the contents of the first worksheet. """ # Make sure we send utf-8 if isinstance(data, str): data = data.encode("utf-8") headers = {"Content-Type": "text/csv"} url = "{}/{}".format(DRIVE_FILES_UPLOAD_API_V2_URL, file_id) res = self.request( "put", url, data=data, params={ "uploadType": "media", "convert": True, "supportsAllDrives": True, }, headers=headers, ) return res.json()
(auth: google.auth.credentials.Credentials, session: Optional[requests.sessions.Session] = None) -> None
708,160
gspread.http_client
request
null
def request( self, method: str, endpoint: str, params: Optional[ParamsType] = None, data: Optional[bytes] = None, json: Optional[Mapping[str, Any]] = None, files: FileType = None, headers: Optional[MutableMapping[str, str]] = None, ) -> Response: response = self.session.request( method=method, url=endpoint, json=json, params=params, data=data, files=files, headers=headers, timeout=self.timeout, ) if response.ok: return response else: raise APIError(response)
(self, method: str, endpoint: str, params: Optional[MutableMapping[str, Union[str, int, bool, float, List[str], NoneType]]] = None, data: Optional[bytes] = None, json: Optional[Mapping[str, Any]] = None, files: Union[MutableMapping[str, IO[Any]], MutableMapping[str, Tuple[str, IO[Any]]], MutableMapping[str, Tuple[str, IO[Any], str]], MutableMapping[str, Tuple[str, IO[Any], str, MutableMapping[str, str]]], NoneType] = None, headers: Optional[MutableMapping[str, str]] = None) -> requests.models.Response
708,171
gspread.exceptions
IncorrectCellLabel
The cell label is incorrect.
class IncorrectCellLabel(GSpreadException): """The cell label is incorrect."""
null
708,172
gspread.exceptions
NoValidUrlKeyFound
No valid key found in URL.
class NoValidUrlKeyFound(GSpreadException): """No valid key found in URL."""
null
708,173
gspread.spreadsheet
Spreadsheet
The class that represents a spreadsheet.
class Spreadsheet: """The class that represents a spreadsheet.""" def __init__(self, http_client: HTTPClient, properties: Dict[str, Any]): self.client = http_client self._properties = properties metadata = self.fetch_sheet_metadata() self._properties.update(metadata["properties"]) @property def id(self): """Spreadsheet ID.""" return self._properties["id"] @property def title(self): """Spreadsheet title.""" return self._properties["title"] @property def url(self): """Spreadsheet URL.""" return SPREADSHEET_DRIVE_URL % self.id @property def creationTime(self): """Spreadsheet Creation time.""" if "createdTime" not in self._properties: self.update_drive_metadata() return self._properties["createdTime"] @property def lastUpdateTime(self): """Spreadsheet last updated time. Only updated on initialisation. For actual last updated time, use get_lastUpdateTime().""" warnings.warn( "worksheet.lastUpdateTime is deprecated, please use worksheet.get_lastUpdateTime()", category=DeprecationWarning, ) if "modifiedTime" not in self._properties: self.update_drive_metadata() return self._properties["modifiedTime"] @property def timezone(self): """Spreadsheet timeZone""" return self._properties["timeZone"] @property def locale(self): """Spreadsheet locale""" return self._properties["locale"] @property def sheet1(self): """Shortcut property for getting the first worksheet.""" return self.get_worksheet(0) def __iter__(self): yield from self.worksheets() def __repr__(self): return "<{} {} id:{}>".format( self.__class__.__name__, repr(self.title), self.id, ) def batch_update(self, body): """Lower-level method that directly calls `spreadsheets/<ID>:batchUpdate <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate>`_. :param dict body: `Batch Update Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate#request-body>`_. :returns: `Batch Update Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate#response-body>`_. :rtype: dict .. versionadded:: 3.0 """ return self.client.batch_update(self.id, body) def values_append(self, range, params, body): """Lower-level method that directly calls `spreadsheets/<ID>/values:append <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of a range to search for a logical table of data. Values will be appended after the last row of the table. :param dict params: `Values Append Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#query-parameters>`_. :param dict body: `Values Append Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#request-body>`_. :returns: `Values Append Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#response-body>`_. :rtype: dict .. versionadded:: 3.0 """ return self.client.values_append(self.id, range, params, body) def values_clear(self, range): """Lower-level method that directly calls `spreadsheets/<ID>/values:clear <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/clear>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to clear. :returns: `Values Clear Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/clear#response-body>`_. :rtype: dict .. versionadded:: 3.0 """ return self.client.values_clear(self.id, range) def values_batch_clear(self, params=None, body=None): """Lower-level method that directly calls `spreadsheets/<ID>/values:batchClear` :param dict params: (optional) `Values Batch Clear Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchClear#path-parameters>`_. :param dict body: (optional) `Values Batch Clear request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchClear#request-body>`_. :rtype: dict """ return self.client.values_batch_clear(self.id, params, body) def values_get(self, range, params=None): """Lower-level method that directly calls `GET spreadsheets/<ID>/values/<range> <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to retrieve. :param dict params: (optional) `Values Get Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get#query-parameters>`_. :returns: `Values Get Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get#response-body>`_. :rtype: dict .. versionadded:: 3.0 """ return self.client.values_get(self.id, range, params=params) def values_batch_get(self, ranges, params=None): """Lower-level method that directly calls `spreadsheets/<ID>/values:batchGet <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchGet>`_. :param list ranges: List of ranges in the `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to retrieve. :param dict params: (optional) `Values Batch Get Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchGet#query-parameters>`_. :returns: `Values Batch Get Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchGet#response-body>`_. :rtype: dict """ return self.client.values_batch_get(self.id, ranges, params=params) def values_update(self, range, params=None, body=None): """Lower-level method that directly calls `PUT spreadsheets/<ID>/values/<range> <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to update. :param dict params: (optional) `Values Update Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update#query-parameters>`_. :param dict body: (optional) `Values Update Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update#request-body>`_. :returns: `Values Update Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update#response-body>`_. :rtype: dict Example:: sh.values_update( 'Sheet1!A2', params={ 'valueInputOption': 'USER_ENTERED' }, body={ 'values': [[1, 2, 3]] } ) .. versionadded:: 3.0 """ return self.client.values_update(self.id, range, params=params, body=body) def values_batch_update(self, body=None): """Lower-level method that directly calls `spreadsheets/<ID>/values:batchUpdate <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdate>`_. :param dict body: (optional) `Values Batch Update Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdate#request-body>`_. :returns: `Values Batch Update Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdate#response-body>`_. :rtype: dict """ return self.client.values_batch_update(self.id, body=body) def _spreadsheets_get(self, params=None): """A method stub that directly calls `spreadsheets.get <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/get>`_.""" return self.client.spreadsheets_get(self.id, params=params) def _spreadsheets_sheets_copy_to(self, sheet_id, destination_spreadsheet_id): """Lower-level method that directly calls `spreadsheets.sheets.copyTo <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.sheets/copyTo>`_.""" return self.client.spreadsheets_sheets_copy_to( self.id, sheet_id, destination_spreadsheet_id ) def fetch_sheet_metadata(self, params=None): """Similar to :method spreadsheets_get:`gspread.http_client.spreadsheets_get`, get the spreadsheet form the API but by default **does not get the cells data**. It only retrieve the the metadata from the spreadsheet. :param dict params: (optional) the HTTP params for the GET request. By default sets the parameter ``includeGridData`` to ``false``. :returns: The raw spreadsheet :rtype: dict """ return self.client.fetch_sheet_metadata(self.id, params=params) def get_worksheet(self, index): """Returns a worksheet with specified `index`. :param index: An index of a worksheet. Indexes start from zero. :type index: int :returns: an instance of :class:`gspread.worksheet.Worksheet`. :raises: :class:`~gspread.exceptions.WorksheetNotFound`: if can't find the worksheet Example. To get third worksheet of a spreadsheet: >>> sht = client.open('My fancy spreadsheet') >>> worksheet = sht.get_worksheet(2) """ sheet_data = self.fetch_sheet_metadata() try: properties = sheet_data["sheets"][index]["properties"] return Worksheet(self, properties, self.id, self.client) except (KeyError, IndexError): raise WorksheetNotFound("index {} not found".format(index)) def get_worksheet_by_id(self, id: Union[str, int]): """Returns a worksheet with specified `worksheet id`. :param id: The id of a worksheet. it can be seen in the url as the value of the parameter 'gid'. :type id: str | int :returns: an instance of :class:`gspread.worksheet.Worksheet`. :raises: :class:`~gspread.exceptions.WorksheetNotFound`: if can't find the worksheet Example. To get the worksheet 123456 of a spreadsheet: >>> sht = client.open('My fancy spreadsheet') >>> worksheet = sht.get_worksheet_by_id(123456) """ sheet_data = self.fetch_sheet_metadata() try: worksheet_id_int = int(id) except ValueError as ex: raise ValueError("id should be int") from ex try: item = finditem( lambda x: x["properties"]["sheetId"] == worksheet_id_int, sheet_data["sheets"], ) return Worksheet(self, item["properties"], self.id, self.client) except (StopIteration, KeyError): raise WorksheetNotFound("id {} not found".format(worksheet_id_int)) def worksheets(self, exclude_hidden: bool = False): """Returns a list of all :class:`worksheets <gspread.worksheet.Worksheet>` in a spreadsheet. :param exclude_hidden: (optional) If set to ``True`` will only return visible worksheets. Default is ``False``. :type exclude_hidden: bool :returns: a list of :class:`worksheets <gspread.worksheet.Worksheet>`. :rtype: list """ sheet_data = self.fetch_sheet_metadata() worksheets = [ Worksheet(self, s["properties"], self.id, self.client) for s in sheet_data["sheets"] ] if exclude_hidden: worksheets = [w for w in worksheets if not w.isSheetHidden] return worksheets def worksheet(self, title): """Returns a worksheet with specified `title`. :param title: A title of a worksheet. If there're multiple worksheets with the same title, first one will be returned. :type title: str :returns: an instance of :class:`gspread.worksheet.Worksheet`. :raises: WorksheetNotFound: if can't find the worksheet Example. Getting worksheet named 'Annual bonuses' >>> sht = client.open('Sample one') >>> worksheet = sht.worksheet('Annual bonuses') """ sheet_data = self.fetch_sheet_metadata() try: item = finditem( lambda x: x["properties"]["title"] == title, sheet_data["sheets"], ) return Worksheet(self, item["properties"], self.id, self.client) except (StopIteration, KeyError): raise WorksheetNotFound(title) def add_worksheet(self, title, rows, cols, index=None): """Adds a new worksheet to a spreadsheet. :param title: A title of a new worksheet. :type title: str :param rows: Number of rows. :type rows: int :param cols: Number of columns. :type cols: int :param index: Position of the sheet. :type index: int :returns: a newly created :class:`worksheets <gspread.worksheet.Worksheet>`. """ body = { "requests": [ { "addSheet": { "properties": { "title": title, "sheetType": "GRID", "gridProperties": { "rowCount": rows, "columnCount": cols, }, } } } ] } if index is not None: body["requests"][0]["addSheet"]["properties"]["index"] = index data = self.client.batch_update(self.id, body) properties = data["replies"][0]["addSheet"]["properties"] return Worksheet(self, properties, self.id, self.client) def duplicate_sheet( self, source_sheet_id, insert_sheet_index=None, new_sheet_id=None, new_sheet_name=None, ): """Duplicates the contents of a sheet. :param int source_sheet_id: The sheet ID to duplicate. :param int insert_sheet_index: (optional) The zero-based index where the new sheet should be inserted. The index of all sheets after this are incremented. :param int new_sheet_id: (optional) The ID of the new sheet. If not set, an ID is chosen. If set, the ID must not conflict with any existing sheet ID. If set, it must be non-negative. :param str new_sheet_name: (optional) The name of the new sheet. If empty, a new name is chosen for you. :returns: a newly created :class:`gspread.worksheet.Worksheet` .. versionadded:: 3.1 """ return Worksheet._duplicate( self.client, self.id, source_sheet_id, self, insert_sheet_index=insert_sheet_index, new_sheet_id=new_sheet_id, new_sheet_name=new_sheet_name, ) def del_worksheet(self, worksheet): """Deletes a worksheet from a spreadsheet. :param worksheet: The worksheet to be deleted. :type worksheet: :class:`~gspread.worksheet.Worksheet` """ body = {"requests": [{"deleteSheet": {"sheetId": worksheet.id}}]} return self.client.batch_update(self.id, body) def del_worksheet_by_id(self, worksheet_id: Union[str, int]): """ Deletes a Worksheet by id """ try: worksheet_id_int = int(worksheet_id) except ValueError as ex: raise ValueError("id should be int") from ex body = {"requests": [{"deleteSheet": {"sheetId": worksheet_id_int}}]} return self.client.batch_update(self.id, body) def reorder_worksheets(self, worksheets_in_desired_order): """Updates the ``index`` property of each Worksheet to reflect its index in the provided sequence of Worksheets. :param worksheets_in_desired_order: Iterable of Worksheet objects in desired order. Note: If you omit some of the Spreadsheet's existing Worksheet objects from the provided sequence, those Worksheets will be appended to the end of the sequence in the order that they appear in the list returned by :meth:`gspread.spreadsheet.Spreadsheet.worksheets`. .. versionadded:: 3.4 """ idx_map = {} for idx, w in enumerate(worksheets_in_desired_order): idx_map[w.id] = idx for w in self.worksheets(): if w.id in idx_map: continue idx += 1 idx_map[w.id] = idx body = { "requests": [ { "updateSheetProperties": { "properties": {"sheetId": key, "index": val}, "fields": "index", } } for key, val in idx_map.items() ] } return self.client.batch_update(self.id, body) def share( self, email_address, perm_type, role, notify=True, email_message=None, with_link=False, ): """Share the spreadsheet with other accounts. :param email_address: user or group e-mail address, domain name or None for 'anyone' type. :type email_address: str, None :param perm_type: The account type. Allowed values are: ``user``, ``group``, ``domain``, ``anyone``. :type perm_type: str :param role: The primary role for this user. Allowed values are: ``owner``, ``writer``, ``reader``. :type role: str :param notify: (optional) Whether to send an email to the target user/domain. :type notify: bool :param email_message: (optional) The email to be sent if notify=True :type email_message: str :param with_link: (optional) Whether the link is required for this permission :type with_link: bool Example:: # Give Otto a write permission on this spreadsheet sh.share('otto@example.com', perm_type='user', role='writer') # Give Otto's family a read permission on this spreadsheet sh.share('otto-familly@example.com', perm_type='group', role='reader') """ return self.client.insert_permission( self.id, email_address=email_address, perm_type=perm_type, role=role, notify=notify, email_message=email_message, with_link=with_link, ) def export(self, format=ExportFormat.PDF): """Export the spreadsheet in the given format. :param str file_id: A key of a spreadsheet to export :param format: The format of the resulting file. Possible values are: ``ExportFormat.PDF``, ``ExportFormat.EXCEL``, ``ExportFormat.CSV``, ``ExportFormat.OPEN_OFFICE_SHEET``, ``ExportFormat.TSV``, and ``ExportFormat.ZIPPED_HTML``. See `ExportFormat`_ in the Drive API. Default value is ``ExportFormat.PDF``. :type format: :class:`~gspread.utils.ExportFormat` :returns bytes: The content of the exported file. .. _ExportFormat: https://developers.google.com/drive/api/guides/ref-export-formats """ return self.client.export(self.id, format) def list_permissions(self): """Lists the spreadsheet's permissions.""" return self.client.list_permissions(self.id) def remove_permissions(self, value, role="any"): """Remove permissions from a user or domain. :param value: User or domain to remove permissions from :type value: str :param role: (optional) Permission to remove. Defaults to all permissions. :type role: str Example:: # Remove Otto's write permission for this spreadsheet sh.remove_permissions('otto@example.com', role='writer') # Remove all Otto's permissions for this spreadsheet sh.remove_permissions('otto@example.com') """ permission_list = self.client.list_permissions(self.id) key = "emailAddress" if "@" in value else "domain" filtered_id_list = [ p["id"] for p in permission_list if p.get(key) == value and (p["role"] == role or role == "any") ] for permission_id in filtered_id_list: self.client.remove_permission(self.id, permission_id) return filtered_id_list def transfer_ownership(self, permission_id): """Transfer the ownership of this file to a new user. It is necessary to first create the permission with the new owner's email address, get the permission ID then use this method to transfer the ownership. .. note:: You can list all permissions using :meth:`gspread.spreadsheet.Spreadsheet.list_permissions`. .. warning:: You can only transfer ownership to a new user, you cannot transfer ownership to a group or a domain email address. """ url = "{}/{}/permissions/{}".format( DRIVE_FILES_API_V3_URL, self.id, permission_id ) payload = { # new owner must be writer in order to accept ownership by editing permissions "role": "writer", "pendingOwner": True, } return self.client.request("patch", url, json=payload) def accept_ownership(self, permission_id): """Accept the pending ownership request on that file. It is necessary to edit the permission with the pending ownership. .. note:: You can only accept ownership transfer for the user currently being used. """ url = "{}/{}/permissions/{}".format( DRIVE_FILES_API_V3_URL, self.id, permission_id, ) payload = { "role": "owner", } params = { "transferOwnership": True, } return self.client.request("patch", url, json=payload, params=params) def named_range(self, named_range): """return a list of :class:`gspread.cell.Cell` objects from the specified named range. :param named_range: A string with a named range value to fetch. :type named_range: str """ # the function `range` does all necessary actions to get a named range. # This is only here to provide better user experience. return self.sheet1.range(named_range) def list_named_ranges(self): """Lists the spreadsheet's named ranges.""" return self.fetch_sheet_metadata(params={"fields": "namedRanges"}).get( "namedRanges", [] ) def update_title(self, title): """Renames the spreadsheet. :param str title: A new title. """ body = { "requests": [ { "updateSpreadsheetProperties": { "properties": {"title": title}, "fields": "title", } } ] } res = self.batch_update(body) self._properties["title"] = title return res def update_timezone(self, timezone): """Updates the current spreadsheet timezone. Can be any timezone in CLDR format such as "America/New_York" or a custom time zone such as GMT-07:00. """ body = { "requests": [ { "updateSpreadsheetProperties": { "properties": {"timeZone": timezone}, "fields": "timeZone", }, }, ] } res = self.batch_update(body) self._properties["timeZone"] = timezone return res def update_locale(self, locale): """Update the locale of the spreadsheet. Can be any of the ISO 639-1 language codes, such as: de, fr, en, ... Or an ISO 639-2 if no ISO 639-1 exists. Or a combination of the ISO language code and country code, such as en_US, de_CH, fr_FR, ... .. note:: Note: when updating this field, not all locales/languages are supported. """ body = { "requests": [ { "updateSpreadsheetProperties": { "properties": {"locale": locale}, "fields": "locale", }, }, ] } res = self.batch_update(body) self._properties["locale"] = locale return res def list_protected_ranges(self, sheetid): """Lists the spreadsheet's protected named ranges""" sheets = self.fetch_sheet_metadata( params={"fields": "sheets.properties,sheets.protectedRanges"} )["sheets"] try: sheet = finditem( lambda sheet: sheet["properties"]["sheetId"] == sheetid, sheets ) except StopIteration: raise WorksheetNotFound("worksheet id {} not found".format(sheetid)) return sheet.get("protectedRanges", []) def get_lastUpdateTime(self) -> str: """Get the lastUpdateTime metadata from the Drive API.""" metadata = self.client.get_file_drive_metadata(self.id) return metadata["modifiedTime"] def update_drive_metadata(self) -> None: """Fetches the drive metadata from the Drive API and updates the cached values in _properties dict.""" drive_metadata = self.client.get_file_drive_metadata(self._properties["id"]) self._properties.update(drive_metadata)
(http_client: gspread.http_client.HTTPClient, properties: Dict[str, Any])
708,174
gspread.spreadsheet
__init__
null
def __init__(self, http_client: HTTPClient, properties: Dict[str, Any]): self.client = http_client self._properties = properties metadata = self.fetch_sheet_metadata() self._properties.update(metadata["properties"])
(self, http_client: gspread.http_client.HTTPClient, properties: Dict[str, Any])
708,177
gspread.spreadsheet
_spreadsheets_get
A method stub that directly calls `spreadsheets.get <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/get>`_.
def _spreadsheets_get(self, params=None): """A method stub that directly calls `spreadsheets.get <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/get>`_.""" return self.client.spreadsheets_get(self.id, params=params)
(self, params=None)
708,178
gspread.spreadsheet
_spreadsheets_sheets_copy_to
Lower-level method that directly calls `spreadsheets.sheets.copyTo <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.sheets/copyTo>`_.
def _spreadsheets_sheets_copy_to(self, sheet_id, destination_spreadsheet_id): """Lower-level method that directly calls `spreadsheets.sheets.copyTo <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.sheets/copyTo>`_.""" return self.client.spreadsheets_sheets_copy_to( self.id, sheet_id, destination_spreadsheet_id )
(self, sheet_id, destination_spreadsheet_id)
708,180
gspread.spreadsheet
add_worksheet
Adds a new worksheet to a spreadsheet. :param title: A title of a new worksheet. :type title: str :param rows: Number of rows. :type rows: int :param cols: Number of columns. :type cols: int :param index: Position of the sheet. :type index: int :returns: a newly created :class:`worksheets <gspread.worksheet.Worksheet>`.
def add_worksheet(self, title, rows, cols, index=None): """Adds a new worksheet to a spreadsheet. :param title: A title of a new worksheet. :type title: str :param rows: Number of rows. :type rows: int :param cols: Number of columns. :type cols: int :param index: Position of the sheet. :type index: int :returns: a newly created :class:`worksheets <gspread.worksheet.Worksheet>`. """ body = { "requests": [ { "addSheet": { "properties": { "title": title, "sheetType": "GRID", "gridProperties": { "rowCount": rows, "columnCount": cols, }, } } } ] } if index is not None: body["requests"][0]["addSheet"]["properties"]["index"] = index data = self.client.batch_update(self.id, body) properties = data["replies"][0]["addSheet"]["properties"] return Worksheet(self, properties, self.id, self.client)
(self, title, rows, cols, index=None)
708,181
gspread.spreadsheet
batch_update
Lower-level method that directly calls `spreadsheets/<ID>:batchUpdate <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate>`_. :param dict body: `Batch Update Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate#request-body>`_. :returns: `Batch Update Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate#response-body>`_. :rtype: dict .. versionadded:: 3.0
def batch_update(self, body): """Lower-level method that directly calls `spreadsheets/<ID>:batchUpdate <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate>`_. :param dict body: `Batch Update Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate#request-body>`_. :returns: `Batch Update Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate#response-body>`_. :rtype: dict .. versionadded:: 3.0 """ return self.client.batch_update(self.id, body)
(self, body)
708,182
gspread.spreadsheet
del_worksheet
Deletes a worksheet from a spreadsheet. :param worksheet: The worksheet to be deleted. :type worksheet: :class:`~gspread.worksheet.Worksheet`
def del_worksheet(self, worksheet): """Deletes a worksheet from a spreadsheet. :param worksheet: The worksheet to be deleted. :type worksheet: :class:`~gspread.worksheet.Worksheet` """ body = {"requests": [{"deleteSheet": {"sheetId": worksheet.id}}]} return self.client.batch_update(self.id, body)
(self, worksheet)
708,183
gspread.spreadsheet
del_worksheet_by_id
Deletes a Worksheet by id
def del_worksheet_by_id(self, worksheet_id: Union[str, int]): """ Deletes a Worksheet by id """ try: worksheet_id_int = int(worksheet_id) except ValueError as ex: raise ValueError("id should be int") from ex body = {"requests": [{"deleteSheet": {"sheetId": worksheet_id_int}}]} return self.client.batch_update(self.id, body)
(self, worksheet_id: Union[str, int])
708,184
gspread.spreadsheet
duplicate_sheet
Duplicates the contents of a sheet. :param int source_sheet_id: The sheet ID to duplicate. :param int insert_sheet_index: (optional) The zero-based index where the new sheet should be inserted. The index of all sheets after this are incremented. :param int new_sheet_id: (optional) The ID of the new sheet. If not set, an ID is chosen. If set, the ID must not conflict with any existing sheet ID. If set, it must be non-negative. :param str new_sheet_name: (optional) The name of the new sheet. If empty, a new name is chosen for you. :returns: a newly created :class:`gspread.worksheet.Worksheet` .. versionadded:: 3.1
def duplicate_sheet( self, source_sheet_id, insert_sheet_index=None, new_sheet_id=None, new_sheet_name=None, ): """Duplicates the contents of a sheet. :param int source_sheet_id: The sheet ID to duplicate. :param int insert_sheet_index: (optional) The zero-based index where the new sheet should be inserted. The index of all sheets after this are incremented. :param int new_sheet_id: (optional) The ID of the new sheet. If not set, an ID is chosen. If set, the ID must not conflict with any existing sheet ID. If set, it must be non-negative. :param str new_sheet_name: (optional) The name of the new sheet. If empty, a new name is chosen for you. :returns: a newly created :class:`gspread.worksheet.Worksheet` .. versionadded:: 3.1 """ return Worksheet._duplicate( self.client, self.id, source_sheet_id, self, insert_sheet_index=insert_sheet_index, new_sheet_id=new_sheet_id, new_sheet_name=new_sheet_name, )
(self, source_sheet_id, insert_sheet_index=None, new_sheet_id=None, new_sheet_name=None)
708,185
gspread.spreadsheet
export
Export the spreadsheet in the given format. :param str file_id: A key of a spreadsheet to export :param format: The format of the resulting file. Possible values are: ``ExportFormat.PDF``, ``ExportFormat.EXCEL``, ``ExportFormat.CSV``, ``ExportFormat.OPEN_OFFICE_SHEET``, ``ExportFormat.TSV``, and ``ExportFormat.ZIPPED_HTML``. See `ExportFormat`_ in the Drive API. Default value is ``ExportFormat.PDF``. :type format: :class:`~gspread.utils.ExportFormat` :returns bytes: The content of the exported file. .. _ExportFormat: https://developers.google.com/drive/api/guides/ref-export-formats
def export(self, format=ExportFormat.PDF): """Export the spreadsheet in the given format. :param str file_id: A key of a spreadsheet to export :param format: The format of the resulting file. Possible values are: ``ExportFormat.PDF``, ``ExportFormat.EXCEL``, ``ExportFormat.CSV``, ``ExportFormat.OPEN_OFFICE_SHEET``, ``ExportFormat.TSV``, and ``ExportFormat.ZIPPED_HTML``. See `ExportFormat`_ in the Drive API. Default value is ``ExportFormat.PDF``. :type format: :class:`~gspread.utils.ExportFormat` :returns bytes: The content of the exported file. .. _ExportFormat: https://developers.google.com/drive/api/guides/ref-export-formats """ return self.client.export(self.id, format)
(self, format=<ExportFormat.PDF: 'application/pdf'>)
708,186
gspread.spreadsheet
fetch_sheet_metadata
Similar to :method spreadsheets_get:`gspread.http_client.spreadsheets_get`, get the spreadsheet form the API but by default **does not get the cells data**. It only retrieve the the metadata from the spreadsheet. :param dict params: (optional) the HTTP params for the GET request. By default sets the parameter ``includeGridData`` to ``false``. :returns: The raw spreadsheet :rtype: dict
def fetch_sheet_metadata(self, params=None): """Similar to :method spreadsheets_get:`gspread.http_client.spreadsheets_get`, get the spreadsheet form the API but by default **does not get the cells data**. It only retrieve the the metadata from the spreadsheet. :param dict params: (optional) the HTTP params for the GET request. By default sets the parameter ``includeGridData`` to ``false``. :returns: The raw spreadsheet :rtype: dict """ return self.client.fetch_sheet_metadata(self.id, params=params)
(self, params=None)
708,187
gspread.spreadsheet
get_lastUpdateTime
Get the lastUpdateTime metadata from the Drive API.
def get_lastUpdateTime(self) -> str: """Get the lastUpdateTime metadata from the Drive API.""" metadata = self.client.get_file_drive_metadata(self.id) return metadata["modifiedTime"]
(self) -> str
708,188
gspread.spreadsheet
get_worksheet
Returns a worksheet with specified `index`. :param index: An index of a worksheet. Indexes start from zero. :type index: int :returns: an instance of :class:`gspread.worksheet.Worksheet`. :raises: :class:`~gspread.exceptions.WorksheetNotFound`: if can't find the worksheet Example. To get third worksheet of a spreadsheet: >>> sht = client.open('My fancy spreadsheet') >>> worksheet = sht.get_worksheet(2)
def get_worksheet(self, index): """Returns a worksheet with specified `index`. :param index: An index of a worksheet. Indexes start from zero. :type index: int :returns: an instance of :class:`gspread.worksheet.Worksheet`. :raises: :class:`~gspread.exceptions.WorksheetNotFound`: if can't find the worksheet Example. To get third worksheet of a spreadsheet: >>> sht = client.open('My fancy spreadsheet') >>> worksheet = sht.get_worksheet(2) """ sheet_data = self.fetch_sheet_metadata() try: properties = sheet_data["sheets"][index]["properties"] return Worksheet(self, properties, self.id, self.client) except (KeyError, IndexError): raise WorksheetNotFound("index {} not found".format(index))
(self, index)
708,189
gspread.spreadsheet
get_worksheet_by_id
Returns a worksheet with specified `worksheet id`. :param id: The id of a worksheet. it can be seen in the url as the value of the parameter 'gid'. :type id: str | int :returns: an instance of :class:`gspread.worksheet.Worksheet`. :raises: :class:`~gspread.exceptions.WorksheetNotFound`: if can't find the worksheet Example. To get the worksheet 123456 of a spreadsheet: >>> sht = client.open('My fancy spreadsheet') >>> worksheet = sht.get_worksheet_by_id(123456)
def get_worksheet_by_id(self, id: Union[str, int]): """Returns a worksheet with specified `worksheet id`. :param id: The id of a worksheet. it can be seen in the url as the value of the parameter 'gid'. :type id: str | int :returns: an instance of :class:`gspread.worksheet.Worksheet`. :raises: :class:`~gspread.exceptions.WorksheetNotFound`: if can't find the worksheet Example. To get the worksheet 123456 of a spreadsheet: >>> sht = client.open('My fancy spreadsheet') >>> worksheet = sht.get_worksheet_by_id(123456) """ sheet_data = self.fetch_sheet_metadata() try: worksheet_id_int = int(id) except ValueError as ex: raise ValueError("id should be int") from ex try: item = finditem( lambda x: x["properties"]["sheetId"] == worksheet_id_int, sheet_data["sheets"], ) return Worksheet(self, item["properties"], self.id, self.client) except (StopIteration, KeyError): raise WorksheetNotFound("id {} not found".format(worksheet_id_int))
(self, id: Union[str, int])
708,195
gspread.spreadsheet
reorder_worksheets
Updates the ``index`` property of each Worksheet to reflect its index in the provided sequence of Worksheets. :param worksheets_in_desired_order: Iterable of Worksheet objects in desired order. Note: If you omit some of the Spreadsheet's existing Worksheet objects from the provided sequence, those Worksheets will be appended to the end of the sequence in the order that they appear in the list returned by :meth:`gspread.spreadsheet.Spreadsheet.worksheets`. .. versionadded:: 3.4
def reorder_worksheets(self, worksheets_in_desired_order): """Updates the ``index`` property of each Worksheet to reflect its index in the provided sequence of Worksheets. :param worksheets_in_desired_order: Iterable of Worksheet objects in desired order. Note: If you omit some of the Spreadsheet's existing Worksheet objects from the provided sequence, those Worksheets will be appended to the end of the sequence in the order that they appear in the list returned by :meth:`gspread.spreadsheet.Spreadsheet.worksheets`. .. versionadded:: 3.4 """ idx_map = {} for idx, w in enumerate(worksheets_in_desired_order): idx_map[w.id] = idx for w in self.worksheets(): if w.id in idx_map: continue idx += 1 idx_map[w.id] = idx body = { "requests": [ { "updateSheetProperties": { "properties": {"sheetId": key, "index": val}, "fields": "index", } } for key, val in idx_map.items() ] } return self.client.batch_update(self.id, body)
(self, worksheets_in_desired_order)
708,196
gspread.spreadsheet
share
Share the spreadsheet with other accounts. :param email_address: user or group e-mail address, domain name or None for 'anyone' type. :type email_address: str, None :param perm_type: The account type. Allowed values are: ``user``, ``group``, ``domain``, ``anyone``. :type perm_type: str :param role: The primary role for this user. Allowed values are: ``owner``, ``writer``, ``reader``. :type role: str :param notify: (optional) Whether to send an email to the target user/domain. :type notify: bool :param email_message: (optional) The email to be sent if notify=True :type email_message: str :param with_link: (optional) Whether the link is required for this permission :type with_link: bool Example:: # Give Otto a write permission on this spreadsheet sh.share('otto@example.com', perm_type='user', role='writer') # Give Otto's family a read permission on this spreadsheet sh.share('otto-familly@example.com', perm_type='group', role='reader')
def share( self, email_address, perm_type, role, notify=True, email_message=None, with_link=False, ): """Share the spreadsheet with other accounts. :param email_address: user or group e-mail address, domain name or None for 'anyone' type. :type email_address: str, None :param perm_type: The account type. Allowed values are: ``user``, ``group``, ``domain``, ``anyone``. :type perm_type: str :param role: The primary role for this user. Allowed values are: ``owner``, ``writer``, ``reader``. :type role: str :param notify: (optional) Whether to send an email to the target user/domain. :type notify: bool :param email_message: (optional) The email to be sent if notify=True :type email_message: str :param with_link: (optional) Whether the link is required for this permission :type with_link: bool Example:: # Give Otto a write permission on this spreadsheet sh.share('otto@example.com', perm_type='user', role='writer') # Give Otto's family a read permission on this spreadsheet sh.share('otto-familly@example.com', perm_type='group', role='reader') """ return self.client.insert_permission( self.id, email_address=email_address, perm_type=perm_type, role=role, notify=notify, email_message=email_message, with_link=with_link, )
(self, email_address, perm_type, role, notify=True, email_message=None, with_link=False)
708,202
gspread.spreadsheet
values_append
Lower-level method that directly calls `spreadsheets/<ID>/values:append <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of a range to search for a logical table of data. Values will be appended after the last row of the table. :param dict params: `Values Append Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#query-parameters>`_. :param dict body: `Values Append Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#request-body>`_. :returns: `Values Append Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#response-body>`_. :rtype: dict .. versionadded:: 3.0
def values_append(self, range, params, body): """Lower-level method that directly calls `spreadsheets/<ID>/values:append <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of a range to search for a logical table of data. Values will be appended after the last row of the table. :param dict params: `Values Append Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#query-parameters>`_. :param dict body: `Values Append Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#request-body>`_. :returns: `Values Append Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#response-body>`_. :rtype: dict .. versionadded:: 3.0 """ return self.client.values_append(self.id, range, params, body)
(self, range, params, body)
708,203
gspread.spreadsheet
values_batch_clear
Lower-level method that directly calls `spreadsheets/<ID>/values:batchClear` :param dict params: (optional) `Values Batch Clear Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchClear#path-parameters>`_. :param dict body: (optional) `Values Batch Clear request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchClear#request-body>`_. :rtype: dict
def values_batch_clear(self, params=None, body=None): """Lower-level method that directly calls `spreadsheets/<ID>/values:batchClear` :param dict params: (optional) `Values Batch Clear Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchClear#path-parameters>`_. :param dict body: (optional) `Values Batch Clear request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchClear#request-body>`_. :rtype: dict """ return self.client.values_batch_clear(self.id, params, body)
(self, params=None, body=None)
708,204
gspread.spreadsheet
values_batch_get
Lower-level method that directly calls `spreadsheets/<ID>/values:batchGet <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchGet>`_. :param list ranges: List of ranges in the `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to retrieve. :param dict params: (optional) `Values Batch Get Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchGet#query-parameters>`_. :returns: `Values Batch Get Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchGet#response-body>`_. :rtype: dict
def values_batch_get(self, ranges, params=None): """Lower-level method that directly calls `spreadsheets/<ID>/values:batchGet <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchGet>`_. :param list ranges: List of ranges in the `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to retrieve. :param dict params: (optional) `Values Batch Get Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchGet#query-parameters>`_. :returns: `Values Batch Get Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchGet#response-body>`_. :rtype: dict """ return self.client.values_batch_get(self.id, ranges, params=params)
(self, ranges, params=None)
708,205
gspread.spreadsheet
values_batch_update
Lower-level method that directly calls `spreadsheets/<ID>/values:batchUpdate <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdate>`_. :param dict body: (optional) `Values Batch Update Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdate#request-body>`_. :returns: `Values Batch Update Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdate#response-body>`_. :rtype: dict
def values_batch_update(self, body=None): """Lower-level method that directly calls `spreadsheets/<ID>/values:batchUpdate <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdate>`_. :param dict body: (optional) `Values Batch Update Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdate#request-body>`_. :returns: `Values Batch Update Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdate#response-body>`_. :rtype: dict """ return self.client.values_batch_update(self.id, body=body)
(self, body=None)
708,206
gspread.spreadsheet
values_clear
Lower-level method that directly calls `spreadsheets/<ID>/values:clear <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/clear>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to clear. :returns: `Values Clear Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/clear#response-body>`_. :rtype: dict .. versionadded:: 3.0
def values_clear(self, range): """Lower-level method that directly calls `spreadsheets/<ID>/values:clear <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/clear>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to clear. :returns: `Values Clear Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/clear#response-body>`_. :rtype: dict .. versionadded:: 3.0 """ return self.client.values_clear(self.id, range)
(self, range)
708,207
gspread.spreadsheet
values_get
Lower-level method that directly calls `GET spreadsheets/<ID>/values/<range> <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to retrieve. :param dict params: (optional) `Values Get Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get#query-parameters>`_. :returns: `Values Get Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get#response-body>`_. :rtype: dict .. versionadded:: 3.0
def values_get(self, range, params=None): """Lower-level method that directly calls `GET spreadsheets/<ID>/values/<range> <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to retrieve. :param dict params: (optional) `Values Get Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get#query-parameters>`_. :returns: `Values Get Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get#response-body>`_. :rtype: dict .. versionadded:: 3.0 """ return self.client.values_get(self.id, range, params=params)
(self, range, params=None)
708,208
gspread.spreadsheet
values_update
Lower-level method that directly calls `PUT spreadsheets/<ID>/values/<range> <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to update. :param dict params: (optional) `Values Update Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update#query-parameters>`_. :param dict body: (optional) `Values Update Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update#request-body>`_. :returns: `Values Update Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update#response-body>`_. :rtype: dict Example:: sh.values_update( 'Sheet1!A2', params={ 'valueInputOption': 'USER_ENTERED' }, body={ 'values': [[1, 2, 3]] } ) .. versionadded:: 3.0
def values_update(self, range, params=None, body=None): """Lower-level method that directly calls `PUT spreadsheets/<ID>/values/<range> <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to update. :param dict params: (optional) `Values Update Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update#query-parameters>`_. :param dict body: (optional) `Values Update Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update#request-body>`_. :returns: `Values Update Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update#response-body>`_. :rtype: dict Example:: sh.values_update( 'Sheet1!A2', params={ 'valueInputOption': 'USER_ENTERED' }, body={ 'values': [[1, 2, 3]] } ) .. versionadded:: 3.0 """ return self.client.values_update(self.id, range, params=params, body=body)
(self, range, params=None, body=None)
708,209
gspread.spreadsheet
worksheet
Returns a worksheet with specified `title`. :param title: A title of a worksheet. If there're multiple worksheets with the same title, first one will be returned. :type title: str :returns: an instance of :class:`gspread.worksheet.Worksheet`. :raises: WorksheetNotFound: if can't find the worksheet Example. Getting worksheet named 'Annual bonuses' >>> sht = client.open('Sample one') >>> worksheet = sht.worksheet('Annual bonuses')
def worksheet(self, title): """Returns a worksheet with specified `title`. :param title: A title of a worksheet. If there're multiple worksheets with the same title, first one will be returned. :type title: str :returns: an instance of :class:`gspread.worksheet.Worksheet`. :raises: WorksheetNotFound: if can't find the worksheet Example. Getting worksheet named 'Annual bonuses' >>> sht = client.open('Sample one') >>> worksheet = sht.worksheet('Annual bonuses') """ sheet_data = self.fetch_sheet_metadata() try: item = finditem( lambda x: x["properties"]["title"] == title, sheet_data["sheets"], ) return Worksheet(self, item["properties"], self.id, self.client) except (StopIteration, KeyError): raise WorksheetNotFound(title)
(self, title)
708,210
gspread.spreadsheet
worksheets
Returns a list of all :class:`worksheets <gspread.worksheet.Worksheet>` in a spreadsheet. :param exclude_hidden: (optional) If set to ``True`` will only return visible worksheets. Default is ``False``. :type exclude_hidden: bool :returns: a list of :class:`worksheets <gspread.worksheet.Worksheet>`. :rtype: list
def worksheets(self, exclude_hidden: bool = False): """Returns a list of all :class:`worksheets <gspread.worksheet.Worksheet>` in a spreadsheet. :param exclude_hidden: (optional) If set to ``True`` will only return visible worksheets. Default is ``False``. :type exclude_hidden: bool :returns: a list of :class:`worksheets <gspread.worksheet.Worksheet>`. :rtype: list """ sheet_data = self.fetch_sheet_metadata() worksheets = [ Worksheet(self, s["properties"], self.id, self.client) for s in sheet_data["sheets"] ] if exclude_hidden: worksheets = [w for w in worksheets if not w.isSheetHidden] return worksheets
(self, exclude_hidden: bool = False)
708,211
gspread.exceptions
SpreadsheetNotFound
Trying to open non-existent or inaccessible spreadsheet.
class SpreadsheetNotFound(GSpreadException): """Trying to open non-existent or inaccessible spreadsheet."""
null
708,212
gspread.worksheet
ValueRange
The class holds the returned values. This class inherit the :const:`list` object type. It behaves exactly like a list. The values are stored in a matrix. The property :meth:`gspread.worksheet.ValueRange.major_dimension` holds the major dimension of the first list level. The inner lists will contain the actual values. Examples:: >>> worksheet.get("A1:B2") [ [ "A1 value", "B1 values", ], [ "A2 value", "B2 value", ] ] >>> worksheet.get("A1:B2").major_dimension ROW .. note:: This class should never be instantiated manually. It will be instantiated using the response from the sheet API.
class ValueRange(list): """The class holds the returned values. This class inherit the :const:`list` object type. It behaves exactly like a list. The values are stored in a matrix. The property :meth:`gspread.worksheet.ValueRange.major_dimension` holds the major dimension of the first list level. The inner lists will contain the actual values. Examples:: >>> worksheet.get("A1:B2") [ [ "A1 value", "B1 values", ], [ "A2 value", "B2 value", ] ] >>> worksheet.get("A1:B2").major_dimension ROW .. note:: This class should never be instantiated manually. It will be instantiated using the response from the sheet API. """ _json: MutableMapping[str, Any] = {} @classmethod def from_json(cls: Type[ValueRangeType], json: Mapping[str, Any]) -> ValueRangeType: values = json.get("values", []) new_obj = cls(values) new_obj._json = { "range": json["range"], "majorDimension": json["majorDimension"], } return new_obj @property def range(self) -> str: """The range of the values""" return self._json["range"] @property def major_dimension(self) -> str: """The major dimension of this range Can be one of: * ``ROW``: the first list level holds rows of values * ``COLUMNS``: the first list level holds columns of values """ return self._json["majorDimension"] def first(self, default: Optional[str] = None) -> Optional[str]: """Returns the value of a first cell in a range. If the range is empty, return the default value. """ try: return self[0][0] except IndexError: return default
(iterable=(), /)
708,213
gspread.worksheet
first
Returns the value of a first cell in a range. If the range is empty, return the default value.
def first(self, default: Optional[str] = None) -> Optional[str]: """Returns the value of a first cell in a range. If the range is empty, return the default value. """ try: return self[0][0] except IndexError: return default
(self, default: Optional[str] = None) -> Optional[str]
708,214
gspread.worksheet
Worksheet
The class that represents a single sheet in a spreadsheet (aka "worksheet").
class Worksheet: """The class that represents a single sheet in a spreadsheet (aka "worksheet"). """ def __init__( self, spreadsheet: "Spreadsheet", properties: MutableMapping[str, Any], spreadsheet_id: Optional[str] = None, client: Optional[HTTPClient] = None, ): # This object is not intended to be created manually # only using gspread code like: spreadsheet.get_worksheet(0) # keep it backward compatible signarure but raise with explicit message # in case of missing new attributes if spreadsheet_id is None or "": raise RuntimeError( """Missing spreadsheet_id parameter, it must be provided with a valid spreadsheet ID. Please allocate new Worksheet object using method like: spreadsheet.get_worksheet(0) """ ) if client is None or not isinstance(client, HTTPClient): raise RuntimeError( """Missing HTTP Client, it must be provided with a valid instance of type gspread.http_client.HTTPClient . Please allocate new Worksheet object using method like: spreadsheet.get_worksheet(0) """ ) self.spreadsheet_id = spreadsheet_id self.client = client self._properties = properties # kept for backward compatibility - publicly available # do not use if possible. self._spreadsheet = spreadsheet def __repr__(self) -> str: return "<{} {} id:{}>".format( self.__class__.__name__, repr(self.title), self.id, ) @property def id(self) -> int: """Worksheet ID.""" return self._properties["sheetId"] @property def spreadsheet(self) -> "Spreadsheet": """Parent spreadsheet""" return self._spreadsheet @property def title(self) -> str: """Worksheet title.""" return self._properties["title"] @property def url(self) -> str: """Worksheet URL.""" return WORKSHEET_DRIVE_URL % (self.spreadsheet_id, self.id) @property def index(self) -> int: """Worksheet index.""" return self._properties["index"] @property def isSheetHidden(self) -> bool: """Worksheet hidden status.""" # if the property is not set then hidden=False return self._properties.get("hidden", False) @property def row_count(self) -> int: """Number of rows.""" return self._properties["gridProperties"]["rowCount"] @property def col_count(self) -> int: """Number of columns. .. warning:: This value is fetched when opening the worksheet. This is not dynamically updated when adding columns, yet. """ return self._properties["gridProperties"]["columnCount"] @property def column_count(self) -> int: """Number of columns""" return self.col_count @property def frozen_row_count(self) -> int: """Number of frozen rows.""" return self._properties["gridProperties"].get("frozenRowCount", 0) @property def frozen_col_count(self) -> int: """Number of frozen columns.""" return self._properties["gridProperties"].get("frozenColumnCount", 0) @property def is_gridlines_hidden(self) -> bool: """Whether or not gridlines hidden. Boolean. True if hidden. False if shown. """ return self._properties["gridProperties"].get("hideGridlines", False) @property def tab_color(self) -> Optional[str]: """Tab color style. Hex with RGB color values.""" return self.get_tab_color() def get_tab_color(self) -> Optional[str]: """Tab color style in hex format. String.""" tab_color = self._properties.get("tabColorStyle", {}).get("rgbColor", None) if tab_color is None: return None return convert_colors_to_hex_value(**tab_color) def _get_sheet_property(self, property: str, default_value: Optional[T]) -> T: """return a property of this worksheet or default value if not found""" meta = self.client.fetch_sheet_metadata(self.spreadsheet_id) sheet = finditem( lambda x: x["properties"]["sheetId"] == self.id, meta["sheets"] ) return sheet.get(property, default_value) def acell( self, label: str, value_render_option: ValueRenderOption = ValueRenderOption.formatted, ) -> Cell: """Returns an instance of a :class:`gspread.cell.Cell`. :param label: Cell label in A1 notation Letter case is ignored. :type label: str :param value_render_option: (optional) Determines how values should be rendered in the output. See `ValueRenderOption`_ in the Sheets API. :type value_render_option: :class:`~gspread.utils.ValueRenderOption` .. _ValueRenderOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueRenderOption Example: >>> worksheet.acell('A1') <Cell R1C1 "I'm cell A1"> """ return self.cell( *(a1_to_rowcol(label)), value_render_option=value_render_option ) def cell( self, row: int, col: int, value_render_option: ValueRenderOption = ValueRenderOption.formatted, ) -> Cell: """Returns an instance of a :class:`gspread.cell.Cell` located at `row` and `col` column. :param row: Row number. :type row: int :param col: Column number. :type col: int :param value_render_option: (optional) Determines how values should be rendered in the output. See `ValueRenderOption`_ in the Sheets API. :type value_render_option: :class:`~gspread.utils.ValueRenderOption` .. _ValueRenderOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueRenderOption Example: >>> worksheet.cell(1, 1) <Cell R1C1 "I'm cell A1"> :rtype: :class:`gspread.cell.Cell` """ try: data = self.get( rowcol_to_a1(row, col), value_render_option=value_render_option, return_type=GridRangeType.ValueRange, ) # we force a return type to GridRangeType.ValueRange # help typing tool to see it too :-) if isinstance(data, ValueRange): value = data.first() else: raise RuntimeError("returned data must be of type ValueRange") except KeyError: value = "" return Cell(row, col, value) @cast_to_a1_notation def range(self, name: str = "") -> List[Cell]: """Returns a list of :class:`gspread.cell.Cell` objects from a specified range. :param name: A string with range value in A1 notation (e.g. 'A1:A5') or the named range to fetch. :type name: str Alternatively, you may specify numeric boundaries. All values index from 1 (one): :param int first_row: First row number :param int first_col: First column number :param int last_row: Last row number :param int last_col: Last column number :rtype: list Example:: >>> # Using A1 notation >>> worksheet.range('A1:B7') [<Cell R1C1 "42">, ...] >>> # Same with numeric boundaries >>> worksheet.range(1, 1, 7, 2) [<Cell R1C1 "42">, ...] >>> # Named ranges work as well >>> worksheet.range('NamedRange') [<Cell R1C1 "42">, ...] >>> # All values in a single API call >>> worksheet.range() [<Cell R1C1 'Hi mom'>, ...] """ range_label = absolute_range_name(self.title, name) data = self.client.values_get(self.spreadsheet_id, range_label) if ":" not in name: name = data.get("range", "") if "!" in name: name = name.split("!")[1] grid_range = a1_range_to_grid_range(name) values = data.get("values", []) row_offset = grid_range.get("startRowIndex", 0) column_offset = grid_range.get("startColumnIndex", 0) last_row = grid_range.get("endRowIndex", self.row_count) last_column = grid_range.get("endColumnIndex", self.col_count) if last_row is not None: last_row -= row_offset if last_column is not None: last_column -= column_offset rect_values = fill_gaps( values, rows=last_row, cols=last_column, ) return [ Cell(row=i + row_offset + 1, col=j + column_offset + 1, value=value) for i, row in enumerate(rect_values) for j, value in enumerate(row) ] def get_values( self, range_name: Optional[str] = None, major_dimension: Optional[Dimension] = None, value_render_option: Optional[ValueRenderOption] = None, date_time_render_option: Optional[DateTimeOption] = None, combine_merged_cells: bool = False, maintain_size: bool = False, pad_values: bool = True, return_type: GridRangeType = GridRangeType.ListOfLists, ) -> List[List[T]]: """Alias for :meth:`~gspread.worksheet.Worksheet.get`... with ``return_type`` set to ``List[List[Any]]`` and ``pad_values`` set to ``True`` (legacy method) """ return self.get( range_name=range_name, major_dimension=major_dimension, value_render_option=value_render_option, date_time_render_option=date_time_render_option, combine_merged_cells=combine_merged_cells, maintain_size=maintain_size, pad_values=pad_values, return_type=return_type, ) def get_all_values( self, range_name: Optional[str] = None, major_dimension: Optional[Dimension] = None, value_render_option: Optional[ValueRenderOption] = None, date_time_render_option: Optional[DateTimeOption] = None, combine_merged_cells: bool = False, maintain_size: bool = False, pad_values: bool = True, return_type: GridRangeType = GridRangeType.ListOfLists, ) -> List[List[T]]: """Alias to :meth:`~gspread.worksheet.Worksheet.get_values`""" return self.get_values( range_name=range_name, major_dimension=major_dimension, value_render_option=value_render_option, date_time_render_option=date_time_render_option, combine_merged_cells=combine_merged_cells, maintain_size=maintain_size, pad_values=pad_values, return_type=return_type, ) def get_all_records( self, head=1, expected_headers=None, value_render_option=None, default_blank="", numericise_ignore=[], allow_underscores_in_numeric_literals=False, empty2zero=False, ) -> List[Dict[str, Union[int, float, str]]]: """Returns a list of dictionaries, all of them having the contents of the spreadsheet with the head row as keys and each of these dictionaries holding the contents of subsequent rows of cells as values. This method uses the function :func:`gspread.utils.to_records` to build the resulting records. It mainly wraps around the function and handle the simplest use case using a header row (default = 1) and the the reste of the entire sheet. .. note:: for any particular use-case, please get your dataset, your headers then use the function :func:`gspread.utils.to_records` to build the records. Cell values are numericised (strings that can be read as ints or floats are converted), unless specified in numericise_ignore :param int head: (optional) Determines which row to use as keys, starting from 1 following the numeration of the spreadsheet. :param list expected_headers: (optional) List of expected headers, they must be unique. .. note:: returned dictionaries will contain all headers even if not included in this list :param value_render_option: (optional) Determines how values should be rendered in the output. See `ValueRenderOption`_ in the Sheets API. :type value_render_option: :class:`~gspread.utils.ValueRenderOption` :param str default_blank: (optional) Determines which value to use for blank cells, defaults to empty string. :param list numericise_ignore: (optional) List of ints of indices of the columns (starting at 1) to ignore numericising, special use of ['all'] to ignore numericising on all columns. :param bool allow_underscores_in_numeric_literals: (optional) Allow underscores in numeric literals, as introduced in PEP 515 :param bool empty2zero: (optional) Determines whether empty cells are converted to zeros when numericised, defaults to False. Examples:: # Sheet data: # A B C # # 1 A1 B2 C3 # 2 A6 B7 C8 # 3 A11 B12 C13 # Read all rows from the sheet >>> worksheet.get_all_records() [ {"A1": "A6", "B2": "B7", "C3": "C8"}, {"A1": "A11", "B2": "B12", "C3": "C13"} ] """ entire_sheet = self.get( value_render_option=value_render_option, pad_values=True, ) if entire_sheet == [[]]: # see test_get_all_records_with_all_values_blank # we don't know the length of the sheet so we return [] return [] keys = entire_sheet[head - 1] values = entire_sheet[head:] if expected_headers is None: # all headers must be unique header_row_is_unique = len(keys) == len(set(keys)) if not header_row_is_unique: raise GSpreadException( "the header row in the worksheet is not unique, " "try passing 'expected_headers' to get_all_records" ) else: # all expected headers must be unique expected_headers_are_unique = len(expected_headers) == len( set(expected_headers) ) if not expected_headers_are_unique: raise GSpreadException("the given 'expected_headers' are not uniques") # expected headers must be a subset of the actual headers if not all(header in keys for header in expected_headers): raise GSpreadException( "the given 'expected_headers' contains unknown headers: " f"{set(expected_headers) - set(keys)}" ) if numericise_ignore == ["all"]: pass else: values = [ numericise_all( row, empty2zero, default_blank, allow_underscores_in_numeric_literals, numericise_ignore, ) for row in values ] return to_records(keys, values) def get_all_cells(self) -> List[Cell]: """Returns a list of all `Cell` of the current sheet.""" return self.range() def row_values( self, row: int, major_dimension: Optional[Dimension] = None, value_render_option: Optional[ValueRenderOption] = None, date_time_render_option: Optional[DateTimeOption] = None, ) -> List[Optional[Union[int, float, str]]]: """Returns a list of all values in a `row`. Empty cells in this list will be rendered as :const:`None`. :param int row: Row number (one-based). :param str major_dimension: (optional) The major dimension of the values. `Dimension.rows` ("ROWS") or `Dimension.cols` ("COLUMNS"). Defaults to Dimension.rows :type major_dimension: :class:`~gspread.utils.Dimension` :param value_render_option: (optional) Determines how values should be rendered in the output. See `ValueRenderOption`_ in the Sheets API. Possible values are: ``ValueRenderOption.formatted`` (default) Values will be calculated and formatted according to the cell's formatting. Formatting is based on the spreadsheet's locale, not the requesting user's locale. ``ValueRenderOption.unformatted`` Values will be calculated, but not formatted in the reply. For example, if A1 is 1.23 and A2 is =A1 and formatted as currency, then A2 would return the number 1.23. ``ValueRenderOption.formula`` Values will not be calculated. The reply will include the formulas. For example, if A1 is 1.23 and A2 is =A1 and formatted as currency, then A2 would return "=A1". .. _ValueRenderOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueRenderOption :type value_render_option: :class:`~gspread.utils.ValueRenderOption` :param date_time_render_option: (optional) How dates, times, and durations should be represented in the output. Possible values are: ``DateTimeOption.serial_number`` (default) Instructs date, time, datetime, and duration fields to be output as doubles in "serial number" format, as popularized by Lotus 1-2-3. ``DateTimeOption.formatted_string`` Instructs date, time, datetime, and duration fields to be output as strings in their given number format (which depends on the spreadsheet locale). .. note:: This is ignored if ``value_render_option`` is ``ValueRenderOption.formatted``. The default ``date_time_render_option`` is ``DateTimeOption.serial_number``. :type date_time_render_option: :class:`~gspread.utils.DateTimeOption` """ try: data = self.get( "A{}:{}".format(row, row), major_dimension, value_render_option, date_time_render_option, ) return data[0] if data else [] except KeyError: return [] def col_values( self, col: int, value_render_option: ValueRenderOption = ValueRenderOption.formatted, ) -> List[Optional[Union[int, float, str]]]: """Returns a list of all values in column `col`. Empty cells in this list will be rendered as :const:`None`. :param int col: Column number (one-based). :param str value_render_option: (optional) Determines how values should be rendered in the output. See `ValueRenderOption`_ in the Sheets API. :type value_render_option: :class:`~gspread.utils.ValueRenderOption` .. _ValueRenderOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueRenderOption """ start_label = rowcol_to_a1(1, col) range_label = "{}:{}".format(start_label, start_label[:-1]) range_name = absolute_range_name(self.title, range_label) data = self.client.values_get( self.spreadsheet_id, range_name, params={ "valueRenderOption": value_render_option, "majorDimension": Dimension.cols, }, ) try: return data["values"][0] except KeyError: return [] def update_acell(self, label: str, value: Union[int, float, str]) -> JSONResponse: """Updates the value of a cell. :param str label: Cell label in A1 notation. :param value: New value. Example:: worksheet.update_acell('A1', '42') """ return self.update_cell(*(a1_to_rowcol(label)), value=value) def update_cell( self, row: int, col: int, value: Union[int, float, str] ) -> JSONResponse: """Updates the value of a cell. :param int row: Row number. :param int col: Column number. :param value: New value. Example:: worksheet.update_cell(1, 1, '42') """ range_name = absolute_range_name(self.title, rowcol_to_a1(row, col)) data = self.client.values_update( self.spreadsheet_id, range_name, params={"valueInputOption": ValueInputOption.user_entered}, body={"values": [[value]]}, ) return data def update_cells( self, cell_list: List[Cell], value_input_option: ValueInputOption = ValueInputOption.raw, ) -> Mapping[str, Any]: """Updates many cells at once. :param list cell_list: List of :class:`gspread.cell.Cell` objects to update. :param value_input_option: (optional) How the input data should be interpreted. Possible values are: ``ValueInputOption.raw`` (default) The values the user has entered will not be parsed and will be stored as-is. ``ValueInputOption.user_entered`` The values will be parsed as if the user typed them into the UI. Numbers will stay as numbers, but strings may be converted to numbers, dates, etc. following the same rules that are applied when entering text into a cell via the Google Sheets UI. See `ValueInputOption`_ in the Sheets API. :type value_input_option: :namedtuple:`~gspread.utils.ValueInputOption` .. _ValueInputOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueInputOption Example:: # Select a range cell_list = worksheet.range('A1:C7') for cell in cell_list: cell.value = 'O_o' # Update in batch worksheet.update_cells(cell_list) """ values_rect = cell_list_to_rect(cell_list) start = rowcol_to_a1( min(c.row for c in cell_list), min(c.col for c in cell_list) ) end = rowcol_to_a1(max(c.row for c in cell_list), max(c.col for c in cell_list)) range_name = absolute_range_name(self.title, "{}:{}".format(start, end)) data = self.client.values_update( self.spreadsheet_id, range_name, params={"valueInputOption": value_input_option}, body={"values": values_rect}, ) return data def get( self, range_name: Optional[str] = None, major_dimension: Optional[Dimension] = None, value_render_option: Optional[ValueRenderOption] = None, date_time_render_option: Optional[DateTimeOption] = None, combine_merged_cells: bool = False, maintain_size: bool = False, pad_values: bool = False, return_type: GridRangeType = GridRangeType.ValueRange, ) -> Union[ValueRange, List[List[Any]]]: """Reads values of a single range or a cell of a sheet. Returns a ValueRange (list of lists) containing all values from a specified range or cell By default values are returned as strings. See ``value_render_option`` to change the default format. :param str range_name: (optional) Cell range in the A1 notation or a named range. If not specified the method returns values from all non empty cells. :param str major_dimension: (optional) The major dimension of the values. `Dimension.rows` ("ROWS") or `Dimension.cols` ("COLUMNS"). Defaults to Dimension.rows :type major_dimension: :class:`~gspread.utils.Dimension` :param value_render_option: (optional) Determines how values should be rendered in the output. See `ValueRenderOption`_ in the Sheets API. Possible values are: ``ValueRenderOption.formatted`` (default) Values will be calculated and formatted according to the cell's formatting. Formatting is based on the spreadsheet's locale, not the requesting user's locale. ``ValueRenderOption.unformatted`` Values will be calculated, but not formatted in the reply. For example, if A1 is 1.23 and A2 is =A1 and formatted as currency, then A2 would return the number 1.23. ``ValueRenderOption.formula`` Values will not be calculated. The reply will include the formulas. For example, if A1 is 1.23 and A2 is =A1 and formatted as currency, then A2 would return "=A1". .. _ValueRenderOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueRenderOption :type value_render_option: :class:`~gspread.utils.ValueRenderOption` :param str date_time_render_option: (optional) How dates, times, and durations should be represented in the output. Possible values are: ``DateTimeOption.serial_number`` (default) Instructs date, time, datetime, and duration fields to be output as doubles in "serial number" format, as popularized by Lotus 1-2-3. ``DateTimeOption.formatted_string`` Instructs date, time, datetime, and duration fields to be output as strings in their given number format (which depends on the spreadsheet locale). .. note:: This is ignored if ``value_render_option`` is ``ValueRenderOption.formatted``. The default ``date_time_render_option`` is ``DateTimeOption.serial_number``. :type date_time_render_option: :class:`~gspread.utils.DateTimeOption` :param bool combine_merged_cells: (optional) If True, then all cells that are part of a merged cell will have the same value as the top-left cell of the merged cell. Defaults to False. .. warning:: Setting this to True will cause an additional API request to be made to retrieve the values of all merged cells. :param bool maintain_size: (optional) If True, then the returned values will have the same size as the requested range_name. Defaults to False. :param bool pad_values: (optional) If True, then empty cells will be filled with empty strings. Defaults to False. .. warning:: The returned array will not be rectangular unless this is set to True. If this is a problem, see also `maintain_size`. :param GridRangeType return_type: (optional) The type of object to return. Defaults to :class:`gspread.utils.GridRangeType.ValueRange`. The other option is `gspread.utils.GridRangeType.ListOfLists`. :rtype: :class:`gspread.worksheet.ValueRange` .. versionadded:: 3.3 Examples:: # Return all values from the sheet worksheet.get() # Return value of 'A1' cell worksheet.get('A1') # Return values of 'A1:B2' range worksheet.get('A1:B2') # Return all values from columns "A" and "B" worksheet.get('A:B') # Return values of 'my_range' named range worksheet.get('my_range') # Return unformatted values (e.g. numbers as numbers) worksheet.get('A2:B4', value_render_option=ValueRenderOption.unformatted) # Return cell values without calculating formulas worksheet.get('A2:B4', value_render_option=ValueRenderOption.formula) """ # do not override the given range name with the build up range name for the actual request get_range_name = absolute_range_name(self.title, range_name) params: ParamsType = { "majorDimension": major_dimension, "valueRenderOption": value_render_option, "dateTimeRenderOption": date_time_render_option, } response = self.client.values_get( self.spreadsheet_id, get_range_name, params=params ) values = response.get("values", [[]]) if pad_values is True: try: values = fill_gaps(values) except KeyError: values = [[]] if combine_merged_cells is True: spreadsheet_meta = self.client.fetch_sheet_metadata(self.spreadsheet_id) worksheet_meta = finditem( lambda x: x["properties"]["title"] == self.title, spreadsheet_meta["sheets"], ) # deal with named ranges named_ranges = spreadsheet_meta.get("namedRanges", []) # if there is a named range with the name range_name if any( range_name == ss_namedRange["name"] for ss_namedRange in named_ranges if ss_namedRange.get("name") ): ss_named_range = finditem( lambda x: x["name"] == range_name, named_ranges ) grid_range = ss_named_range.get("range", {}) # norrmal range_name, i.e., A1:B2 elif range_name is not None: a1 = get_a1_from_absolute_range(range_name) grid_range = a1_range_to_grid_range(a1) # no range_name, i.e., all values else: grid_range = worksheet_meta.get("basicFilter", {}).get("range", {}) values = combined_merge_values( worksheet_metadata=worksheet_meta, values=values, start_row_index=grid_range.get("startRowIndex", 0), start_col_index=grid_range.get("startColumnIndex", 0), ) # In case range_name is None range_name = range_name or "" # range_name must be a full grid range so that we can guarantee # startRowIndex and endRowIndex properties if maintain_size is True and is_full_a1_notation(range_name): a1_range = get_a1_from_absolute_range(range_name) grid_range = a1_range_to_grid_range(a1_range) rows = grid_range["endRowIndex"] - grid_range["startRowIndex"] cols = grid_range["endColumnIndex"] - grid_range["startColumnIndex"] values = fill_gaps(values, rows=rows, cols=cols) if return_type is GridRangeType.ValueRange: response["values"] = values return ValueRange.from_json(response) if return_type is GridRangeType.ListOfLists: return values raise ValueError("return_type must be either ValueRange or ListOfLists") def batch_get( self, ranges: Iterable[str], major_dimension: Optional[Dimension] = None, value_render_option: Optional[ValueRenderOption] = None, date_time_render_option: Optional[DateTimeOption] = None, ) -> List[ValueRange]: """Returns one or more ranges of values from the sheet. :param list ranges: List of cell ranges in the A1 notation or named ranges. :param str major_dimension: (optional) The major dimension of the values. `Dimension.rows` ("ROWS") or `Dimension.cols` ("COLUMNS"). Defaults to Dimension.rows :type major_dimension: :class:`~gspread.utils.Dimension` :param value_render_option: (optional) Determines how values should be rendered in the output. See `ValueRenderOption`_ in the Sheets API. Possible values are: ``ValueRenderOption.formatted`` (default) Values will be calculated and formatted according to the cell's formatting. Formatting is based on the spreadsheet's locale, not the requesting user's locale. ``ValueRenderOption.unformatted`` Values will be calculated, but not formatted in the reply. For example, if A1 is 1.23 and A2 is =A1 and formatted as currency, then A2 would return the number 1.23. ``ValueRenderOption.formula`` Values will not be calculated. The reply will include the formulas. For example, if A1 is 1.23 and A2 is =A1 and formatted as currency, then A2 would return "=A1". .. _ValueRenderOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueRenderOption :type value_render_option: :class:`~gspread.utils.ValueRenderOption` :param str date_time_render_option: (optional) How dates, times, and durations should be represented in the output. Possible values are: ``DateTimeOption.serial_number`` (default) Instructs date, time, datetime, and duration fields to be output as doubles in "serial number" format, as popularized by Lotus 1-2-3. ``DateTimeOption.formatted_string`` Instructs date, time, datetime, and duration fields to be output as strings in their given number format (which depends on the spreadsheet locale). .. note:: This is ignored if ``value_render_option`` is ``ValueRenderOption.formatted``. The default ``date_time_render_option`` is ``DateTimeOption.serial_number``. :type date_time_render_option: :class:`~gspread.utils.DateTimeOption` .. versionadded:: 3.3 Examples:: # Read values from 'A1:B2' range and 'F12' cell worksheet.batch_get(['A1:B2', 'F12']) """ ranges = [absolute_range_name(self.title, r) for r in ranges if r] params: ParamsType = { "majorDimension": major_dimension, "valueRenderOption": value_render_option, "dateTimeRenderOption": date_time_render_option, } response = self.client.values_batch_get( self.spreadsheet_id, ranges=ranges, params=params ) return [ValueRange.from_json(x) for x in response["valueRanges"]] def update( self, values: Iterable[Iterable[Any]], range_name: Optional[str] = None, raw: bool = True, major_dimension: Optional[Dimension] = None, value_input_option: Optional[ValueInputOption] = None, include_values_in_response: Optional[bool] = None, response_value_render_option: Optional[ValueRenderOption] = None, response_date_time_render_option: Optional[DateTimeOption] = None, ) -> JSONResponse: """Sets values in a cell range of the sheet. :param list values: The data to be written in a matrix format. :param str range_name: (optional) The A1 notation of the values to update. :param bool raw: The values will not be parsed by Sheets API and will be stored as-is. For example, formulas will be rendered as plain strings. Defaults to ``True``. This is a shortcut for the ``value_input_option`` parameter. :param str major_dimension: (optional) The major dimension of the values. `Dimension.rows` ("ROWS") or `Dimension.cols` ("COLUMNS"). Defaults to Dimension.rows :type major_dimension: :class:`~gspread.utils.Dimension` :param str value_input_option: (optional) How the input data should be interpreted. Possible values are: ``ValueInputOption.raw`` (default) The values the user has entered will not be parsed and will be stored as-is. ``ValueInputOption.user_entered`` The values will be parsed as if the user typed them into the UI. Numbers will stay as numbers, but strings may be converted to numbers, dates, etc. following the same rules that are applied when entering text into a cell via the Google Sheets UI. :type value_input_option: :class:`~gspread.utils.ValueInputOption` :param response_value_render_option: (optional) Determines how values should be rendered in the output. See `ValueRenderOption`_ in the Sheets API. Possible values are: ``ValueRenderOption.formatted`` (default) Values will be calculated and formatted according to the cell's formatting. Formatting is based on the spreadsheet's locale, not the requesting user's locale. ``ValueRenderOption.unformatted`` Values will be calculated, but not formatted in the reply. For example, if A1 is 1.23 and A2 is =A1 and formatted as currency, then A2 would return the number 1.23. ``ValueRenderOption.formula`` Values will not be calculated. The reply will include the formulas. For example, if A1 is 1.23 and A2 is =A1 and formatted as currency, then A2 would return "=A1". .. _ValueRenderOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueRenderOption :type response_value_render_option: :class:`~gspread.utils.ValueRenderOption` :param str response_date_time_render_option: (optional) How dates, times, and durations should be represented in the output. Possible values are: ``DateTimeOption.serial_number`` (default) Instructs date, time, datetime, and duration fields to be output as doubles in "serial number" format, as popularized by Lotus 1-2-3. ``DateTimeOption.formatted_string`` Instructs date, time, datetime, and duration fields to be output as strings in their given number format (which depends on the spreadsheet locale). .. note:: This is ignored if ``value_render_option`` is ``ValueRenderOption.formatted``. The default ``date_time_render_option`` is ``DateTimeOption.serial_number``. :type date_time_render_option: :class:`~gspread.utils.DateTimeOption` Examples:: # Sets 'Hello world' in 'A2' cell worksheet.update([['Hello world']], 'A2') # Updates cells A1, B1, C1 with values 42, 43, 44 respectively worksheet.update([[42, 43, 44]]) # Updates A2 and A3 with values 42 and 43 # Note that update range can be bigger than values array worksheet.update([[42], [43]], 'A2:B4') # Add a formula worksheet.update([['=SUM(A1:A4)']], 'A5', raw=False) # Update 'my_range' named range with values 42 and 43 worksheet.update([[42], [43]], 'my_range') # Note: named ranges are defined in the scope of # a spreadsheet, so even if `my_range` does not belong to # this sheet it is still updated .. versionadded:: 3.3 """ if isinstance(range_name, (list, tuple)) and isinstance(values, str): warnings.warn( "The order of arguments in worksheet.update() has changed. " "Please pass values first and range_name second" "or used named arguments (range_name=, values=)", DeprecationWarning, stacklevel=2, ) range_name, values = values, range_name full_range_name = absolute_range_name(self.title, range_name) if not value_input_option: value_input_option = ( ValueInputOption.raw if raw is True else ValueInputOption.user_entered ) params: ParamsType = { "valueInputOption": value_input_option, "includeValuesInResponse": include_values_in_response, "responseValueRenderOption": response_value_render_option, "responseDateTimeRenderOption": response_date_time_render_option, } response = self.client.values_update( self.spreadsheet_id, full_range_name, params=params, body={"values": values, "majorDimension": major_dimension}, ) return response def batch_update( self, data: Iterable[MutableMapping[str, Any]], raw: bool = True, value_input_option: Optional[ValueInputOption] = None, include_values_in_response: Optional[bool] = None, response_value_render_option: Optional[ValueRenderOption] = None, response_date_time_render_option: Optional[DateTimeOption] = None, ) -> JSONResponse: """Sets values in one or more cell ranges of the sheet at once. :param list data: List of dictionaries in the form of `{'range': '...', 'values': [[.., ..], ...]}` where `range` is a target range to update in A1 notation or a named range, and `values` is a list of lists containing new values. :param str value_input_option: (optional) How the input data should be interpreted. Possible values are: * ``ValueInputOption.raw`` The values the user has entered will not be parsed and will be stored as-is. * ``ValueInputOption.user_entered`` The values will be parsed as if the user typed them into the UI. Numbers will stay as numbers, but strings may be converted to numbers, dates, etc. following the same rules that are applied when entering text into a cell via the Google Sheets UI. :type value_input_option: :class:`~gspread.utils.ValueInputOption` :param response_value_render_option: (optional) Determines how values should be rendered in the output. See `ValueRenderOption`_ in the Sheets API. Possible values are: ``ValueRenderOption.formatted`` (default) Values will be calculated and formatted according to the cell's formatting. Formatting is based on the spreadsheet's locale, not the requesting user's locale. ``ValueRenderOption.unformatted`` Values will be calculated, but not formatted in the reply. For example, if A1 is 1.23 and A2 is =A1 and formatted as currency, then A2 would return the number 1.23. ``ValueRenderOption.formula`` Values will not be calculated. The reply will include the formulas. For example, if A1 is 1.23 and A2 is =A1 and formatted as currency, then A2 would return "=A1". .. _ValueRenderOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueRenderOption :type response_value_render_option: :class:`~gspread.utils.ValueRenderOption` :param str response_date_time_render_option: (optional) How dates, times, and durations should be represented in the output. Possible values are: ``DateTimeOption.serial_number`` (default) Instructs date, time, datetime, and duration fields to be output as doubles in "serial number" format, as popularized by Lotus 1-2-3. ``DateTimeOption.formatted_string`` Instructs date, time, datetime, and duration fields to be output as strings in their given number format (which depends on the spreadsheet locale). .. note:: This is ignored if ``value_render_option`` is ``ValueRenderOption.formatted``. The default ``date_time_render_option`` is ``DateTimeOption.serial_number``. :type date_time_render_option: :class:`~gspread.utils.DateTimeOption` Examples:: worksheet.batch_update([{ 'range': 'A1:B1', 'values': [['42', '43']], }, { 'range': 'my_range', 'values': [['44', '45']], }]) # Note: named ranges are defined in the scope of # a spreadsheet, so even if `my_range` does not belong to # this sheet it is still updated .. versionadded:: 3.3 """ if not value_input_option: value_input_option = ( ValueInputOption.raw if raw is True else ValueInputOption.user_entered ) for values in data: values["range"] = absolute_range_name(self.title, values["range"]) body: MutableMapping[str, Any] = { "valueInputOption": value_input_option, "includeValuesInResponse": include_values_in_response, "responseValueRenderOption": response_value_render_option, "responseDateTimeRenderOption": response_date_time_render_option, "data": data, } response = self.client.values_batch_update(self.spreadsheet_id, body=body) return response def batch_format(self, formats: List[CellFormat]) -> JSONResponse: """Formats cells in batch. :param list formats: List of ranges to format and the new format to apply to each range. The list is composed of dict objects with the following keys/values: * range : A1 range notation * format : a valid dict object with the format to apply for that range see `CellFormat`_ in the Sheets API for available fields. .. _CellFormat: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/cells#cellformat Examples:: # Format the range ``A1:C1`` with bold text # and format the range ``A2:C2`` a font size of 16 formats = [ { "range": "A1:C1", "format": { "textFormat": { "bold": True, }, }, }, { "range": "A2:C2", "format": { "textFormat": { "fontSize": 16, }, }, }, ] worksheet.batch_format(formats) .. versionadded:: 5.4 """ # No need to type more than that it's only internal to that method body: Dict[str, Any] = { "requests": [], } for format in formats: range_name = format["range"] cell_format = format["format"] grid_range = a1_range_to_grid_range(range_name, self.id) fields = "userEnteredFormat(%s)" % ",".join(cell_format.keys()) body["requests"].append( { "repeatCell": { "range": grid_range, "cell": {"userEnteredFormat": cell_format}, "fields": fields, } } ) return self.client.batch_update(self.spreadsheet_id, body) def format( self, ranges: Union[List[str], str], format: JSONResponse ) -> JSONResponse: """Format a list of ranges with the given format. :param str|list ranges: Target ranges in the A1 notation. :param dict format: Dictionary containing the fields to update. See `CellFormat`_ in the Sheets API for available fields. Examples:: # Set 'A4' cell's text format to bold worksheet.format("A4", {"textFormat": {"bold": True}}) # Set 'A1:D4' and 'A10:D10' cells's text format to bold worksheet.format(["A1:D4", "A10:D10"], {"textFormat": {"bold": True}}) # Color the background of 'A2:B2' cell range in black, # change horizontal alignment, text color and font size worksheet.format("A2:B2", { "backgroundColor": { "red": 0.0, "green": 0.0, "blue": 0.0 }, "horizontalAlignment": "CENTER", "textFormat": { "foregroundColor": { "red": 1.0, "green": 1.0, "blue": 1.0 }, "fontSize": 12, "bold": True } }) .. versionadded:: 3.3 """ if isinstance(ranges, list): range_list = ranges else: range_list = [ranges] formats = [CellFormat(range=range, format=format) for range in range_list] return self.batch_format(formats) def resize( self, rows: Optional[int] = None, cols: Optional[int] = None ) -> JSONResponse: """Resizes the worksheet. Specify one of ``rows`` or ``cols``. :param int rows: (optional) New number of rows. :param int cols: (optional) New number columns. """ grid_properties = {} if rows is not None: grid_properties["rowCount"] = rows if cols is not None: grid_properties["columnCount"] = cols if not grid_properties: raise TypeError("Either 'rows' or 'cols' should be specified.") fields = ",".join("gridProperties/%s" % p for p in grid_properties.keys()) body = { "requests": [ { "updateSheetProperties": { "properties": { "sheetId": self.id, "gridProperties": grid_properties, }, "fields": fields, } } ] } res = self.client.batch_update(self.spreadsheet_id, body) if rows is not None: self._properties["gridProperties"]["rowCount"] = rows if cols is not None: self._properties["gridProperties"]["columnCount"] = cols return res def sort( self, *specs: Tuple[int, Literal["asc", "des"]], range: Optional[str] = None ) -> JSONResponse: """Sorts worksheet using given sort orders. :param list specs: The sort order per column. Each sort order represented by a tuple where the first element is a column index and the second element is the order itself: 'asc' or 'des'. :param str range: The range to sort in A1 notation. By default sorts the whole sheet excluding frozen rows. Example:: # Sort sheet A -> Z by column 'B' wks.sort((2, 'asc')) # Sort range A2:G8 basing on column 'G' A -> Z # and column 'B' Z -> A wks.sort((7, 'asc'), (2, 'des'), range='A2:G8') .. versionadded:: 3.4 """ if range: start_a1, end_a1 = range.split(":") start_row, start_col = a1_to_rowcol(start_a1) end_row, end_col = a1_to_rowcol(end_a1) else: start_row = self._properties["gridProperties"].get("frozenRowCount", 0) + 1 start_col = 1 end_row = self.row_count end_col = self.col_count request_range = { "sheetId": self.id, "startRowIndex": start_row - 1, "endRowIndex": end_row, "startColumnIndex": start_col - 1, "endColumnIndex": end_col, } request_sort_specs = list() for col, order in specs: if order == "asc": request_order = "ASCENDING" elif order == "des": request_order = "DESCENDING" else: raise ValueError( "Either 'asc' or 'des' should be specified as sort order." ) request_sort_spec = { "dimensionIndex": col - 1, "sortOrder": request_order, } request_sort_specs.append(request_sort_spec) body = { "requests": [ { "sortRange": { "range": request_range, "sortSpecs": request_sort_specs, } } ] } response = self.client.batch_update(self.spreadsheet_id, body) return response def update_title(self, title: str) -> JSONResponse: """Renames the worksheet. :param str title: A new title. """ body = { "requests": [ { "updateSheetProperties": { "properties": {"sheetId": self.id, "title": title}, "fields": "title", } } ] } response = self.client.batch_update(self.spreadsheet_id, body) self._properties["title"] = title return response def update_tab_color(self, color: str) -> JSONResponse: """Changes the worksheet's tab color. Use clear_tab_color() to remove the color. :param str color: Hex color value. """ color_dict = convert_hex_to_colors_dict(color) body = { "requests": [ { "updateSheetProperties": { "properties": { "sheetId": self.id, "tabColorStyle": { "rgbColor": color_dict, }, }, "fields": "tabColorStyle", } } ] } response = self.client.batch_update(self.spreadsheet_id, body) self._properties["tabColorStyle"] = {"rgbColor": color_dict} return response def clear_tab_color(self) -> JSONResponse: """Clears the worksheet's tab color. Use update_tab_color() to set the color. """ body = { "requests": [ { "updateSheetProperties": { "properties": { "sheetId": self.id, "tabColorStyle": { "rgbColor": None, }, }, "fields": "tabColorStyle", }, }, ], } response = self.client.batch_update(self.spreadsheet_id, body) self._properties.pop("tabColorStyle") return response def update_index(self, index: int) -> JSONResponse: """Updates the ``index`` property for the worksheet. See the `Sheets API documentation <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets#sheetproperties>`_ for information on how updating the index property affects the order of worksheets in a spreadsheet. To reorder all worksheets in a spreadsheet, see `Spreadsheet.reorder_worksheets`. .. versionadded:: 3.4 """ body = { "requests": [ { "updateSheetProperties": { "properties": {"sheetId": self.id, "index": index}, "fields": "index", } } ] } res = self.client.batch_update(self.spreadsheet_id, body) self._properties["index"] = index return res def _auto_resize( self, start_index: int, end_index: int, dimension: Dimension ) -> JSONResponse: """Updates the size of rows or columns in the worksheet. Index start from 0 :param start_index: The index (inclusive) to begin resizing :param end_index: The index (exclusive) to finish resizing :param dimension: Specifies whether to resize the row or column :type major_dimension: :class:`~gspread.utils.Dimension` .. versionadded:: 5.3.3 """ body = { "requests": [ { "autoResizeDimensions": { "dimensions": { "sheetId": self.id, "dimension": dimension, "startIndex": start_index, "endIndex": end_index, } } } ] } return self.client.batch_update(self.spreadsheet_id, body) def columns_auto_resize( self, start_column_index: int, end_column_index: int ) -> JSONResponse: """Updates the size of rows or columns in the worksheet. Index start from 0 :param start_column_index: The index (inclusive) to begin resizing :param end_column_index: The index (exclusive) to finish resizing .. versionadded:: 3.4 .. versionchanged:: 5.3.3 """ return self._auto_resize(start_column_index, end_column_index, Dimension.cols) def rows_auto_resize( self, start_row_index: int, end_row_index: int ) -> JSONResponse: """Updates the size of rows or columns in the worksheet. Index start from 0 :param start_row_index: The index (inclusive) to begin resizing :param end_row_index: The index (exclusive) to finish resizing .. versionadded:: 5.3.3 """ return self._auto_resize(start_row_index, end_row_index, Dimension.rows) def add_rows(self, rows: int) -> None: """Adds rows to worksheet. :param rows: Number of new rows to add. :type rows: int """ self.resize(rows=self.row_count + rows) def add_cols(self, cols: int) -> None: """Adds columns to worksheet. :param cols: Number of new columns to add. :type cols: int """ self.resize(cols=self.col_count + cols) def append_row( self, values: Sequence[Union[str, int, float]], value_input_option: ValueInputOption = ValueInputOption.raw, insert_data_option: Optional[InsertDataOption] = None, table_range: Optional[str] = None, include_values_in_response: bool = False, ) -> JSONResponse: """Adds a row to the worksheet and populates it with values. Widens the worksheet if there are more values than columns. :param list values: List of values for the new row. :param value_input_option: (optional) Determines how the input data should be interpreted. See `ValueInputOption`_ in the Sheets API reference. :type value_input_option: :class:`~gspread.utils.ValueInputOption` :param str insert_data_option: (optional) Determines how the input data should be inserted. See `InsertDataOption`_ in the Sheets API reference. :param str table_range: (optional) The A1 notation of a range to search for a logical table of data. Values are appended after the last row of the table. Examples: ``A1`` or ``B2:D4`` :param bool include_values_in_response: (optional) Determines if the update response should include the values of the cells that were appended. By default, responses do not include the updated values. .. _ValueInputOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueInputOption .. _InsertDataOption: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#InsertDataOption """ return self.append_rows( [values], value_input_option=value_input_option, insert_data_option=insert_data_option, table_range=table_range, include_values_in_response=include_values_in_response, ) def append_rows( self, values: Sequence[Sequence[Union[str, int, float]]], value_input_option: ValueInputOption = ValueInputOption.raw, insert_data_option: Optional[InsertDataOption] = None, table_range: Optional[str] = None, include_values_in_response: Optional[bool] = None, ) -> JSONResponse: """Adds multiple rows to the worksheet and populates them with values. Widens the worksheet if there are more values than columns. :param list values: List of rows each row is List of values for the new row. :param value_input_option: (optional) Determines how input data should be interpreted. Possible values are ``ValueInputOption.raw`` or ``ValueInputOption.user_entered``. See `ValueInputOption`_ in the Sheets API. :type value_input_option: :class:`~gspread.utils.ValueInputOption` :param str insert_data_option: (optional) Determines how the input data should be inserted. See `InsertDataOption`_ in the Sheets API reference. :param str table_range: (optional) The A1 notation of a range to search for a logical table of data. Values are appended after the last row of the table. Examples: ``A1`` or ``B2:D4`` :param bool include_values_in_response: (optional) Determines if the update response should include the values of the cells that were appended. By default, responses do not include the updated values. .. _ValueInputOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueInputOption .. _InsertDataOption: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#InsertDataOption """ range_label = absolute_range_name(self.title, table_range) params: ParamsType = { "valueInputOption": value_input_option, "insertDataOption": insert_data_option, "includeValuesInResponse": include_values_in_response, } body = {"values": values} res = self.client.values_append(self.spreadsheet_id, range_label, params, body) num_new_rows = len(values) self._properties["gridProperties"]["rowCount"] += num_new_rows return res def insert_row( self, values: Sequence[Union[str, int, float]], index: int = 1, value_input_option: ValueInputOption = ValueInputOption.raw, inherit_from_before: bool = False, ) -> JSONResponse: """Adds a row to the worksheet at the specified index and populates it with values. Widens the worksheet if there are more values than columns. :param list values: List of values for the new row. :param int index: (optional) Offset for the newly inserted row. :param str value_input_option: (optional) Determines how input data should be interpreted. Possible values are ``ValueInputOption.raw`` or ``ValueInputOption.user_entered``. See `ValueInputOption`_ in the Sheets API. :type value_input_option: :class:`~gspread.utils.ValueInputOption` :param bool inherit_from_before: (optional) If True, the new row will inherit its properties from the previous row. Defaults to False, meaning that the new row acquires the properties of the row immediately after it. .. warning:: `inherit_from_before` must be False when adding a row to the top of a spreadsheet (`index=1`), and must be True when adding to the bottom of the spreadsheet. .. _ValueInputOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueInputOption """ return self.insert_rows( [values], index, value_input_option=value_input_option, inherit_from_before=inherit_from_before, ) def insert_rows( self, values: Sequence[Sequence[Union[str, int, float]]], row: int = 1, value_input_option: ValueInputOption = ValueInputOption.raw, inherit_from_before: bool = False, ) -> JSONResponse: """Adds multiple rows to the worksheet at the specified index and populates them with values. :param list values: List of row lists. a list of lists, with the lists each containing one row's values. Widens the worksheet if there are more values than columns. :param int row: Start row to update (one-based). Defaults to 1 (one). :param str value_input_option: (optional) Determines how input data should be interpreted. Possible values are ``ValueInputOption.raw`` or ``ValueInputOption.user_entered``. See `ValueInputOption`_ in the Sheets API. :type value_input_option: :class:`~gspread.utils.ValueInputOption` :param bool inherit_from_before: (optional) If true, new rows will inherit their properties from the previous row. Defaults to False, meaning that new rows acquire the properties of the row immediately after them. .. warning:: `inherit_from_before` must be False when adding rows to the top of a spreadsheet (`row=1`), and must be True when adding to the bottom of the spreadsheet. """ # can't insert row on sheet with colon ':' # in its name, see issue: https://issuetracker.google.com/issues/36761154 if ":" in self.title: raise GSpreadException( "can't insert row in worksheet with colon ':' in its name. See issue: https://issuetracker.google.com/issues/36761154" ) if inherit_from_before and row == 1: raise GSpreadException( "inherit_from_before cannot be used when inserting row(s) at the top of a spreadsheet" ) insert_dimension_body = { "requests": [ { "insertDimension": { "range": { "sheetId": self.id, "dimension": Dimension.rows, "startIndex": row - 1, "endIndex": len(values) + row - 1, }, "inheritFromBefore": inherit_from_before, } } ] } self.client.batch_update(self.spreadsheet_id, insert_dimension_body) range_label = absolute_range_name(self.title, "A%s" % row) params: ParamsType = {"valueInputOption": value_input_option} body = {"majorDimension": Dimension.rows, "values": values} res = self.client.values_append(self.spreadsheet_id, range_label, params, body) num_new_rows = len(values) self._properties["gridProperties"]["rowCount"] += num_new_rows return res def insert_cols( self, values: Sequence[Sequence[Union[str, int, float]]], col: int = 1, value_input_option: ValueInputOption = ValueInputOption.raw, inherit_from_before: bool = False, ) -> JSONResponse: """Adds multiple new cols to the worksheet at specified index and populates them with values. :param list values: List of col lists. a list of lists, with the lists each containing one col's values. Increases the number of rows if there are more values than columns. :param int col: Start col to update (one-based). Defaults to 1 (one). :param str value_input_option: (optional) Determines how input data should be interpreted. Possible values are ``ValueInputOption.raw`` or ``ValueInputOption.user_entered``. See `ValueInputOption`_ in the Sheets API. :type value_input_option: :class:`~gspread.utils.ValueInputOption` :param bool inherit_from_before: (optional) If True, new columns will inherit their properties from the previous column. Defaults to False, meaning that new columns acquire the properties of the column immediately after them. .. warning:: `inherit_from_before` must be False if adding at the left edge of a spreadsheet (`col=1`), and must be True if adding at the right edge of the spreadsheet. """ if inherit_from_before and col == 1: raise GSpreadException( "inherit_from_before cannot be used when inserting column(s) at the left edge of a spreadsheet" ) insert_dimension_body = { "requests": [ { "insertDimension": { "range": { "sheetId": self.id, "dimension": Dimension.cols, "startIndex": col - 1, "endIndex": len(values) + col - 1, }, "inheritFromBefore": inherit_from_before, } } ] } self.client.batch_update(self.spreadsheet_id, insert_dimension_body) range_label = absolute_range_name(self.title, rowcol_to_a1(1, col)) params: ParamsType = {"valueInputOption": value_input_option} body = {"majorDimension": Dimension.cols, "values": values} res = self.client.values_append(self.spreadsheet_id, range_label, params, body) num_new_cols = len(values) self._properties["gridProperties"]["columnCount"] += num_new_cols return res @cast_to_a1_notation def add_protected_range( self, name: str, editor_users_emails: Sequence[str] = [], editor_groups_emails: Sequence[str] = [], description: Optional[str] = None, warning_only: bool = False, requesting_user_can_edit: bool = False, ) -> JSONResponse: """Add protected range to the sheet. Only the editors can edit the protected range. Google API will automatically add the owner of this SpreadSheet. The list ``editor_users_emails`` must at least contain the e-mail address used to open that SpreadSheet. ``editor_users_emails`` must only contain e-mail addresses who already have a write access to the spreadsheet. :param str name: A string with range value in A1 notation, e.g. 'A1:A5'. Alternatively, you may specify numeric boundaries. All values index from 1 (one): :param int first_row: First row number :param int first_col: First column number :param int last_row: Last row number :param int last_col: Last column number For both A1 and numeric notation: :param list editor_users_emails: The email addresses of users with edit access to the protected range. This must include your e-mail address at least. :param list editor_groups_emails: (optional) The email addresses of groups with edit access to the protected range. :param str description: (optional) Description for the protected ranges. :param boolean warning_only: (optional) When true this protected range will show a warning when editing. Defaults to ``False``. :param boolean requesting_user_can_edit: (optional) True if the user who requested this protected range can edit the protected cells. Defaults to ``False``. """ grid_range = a1_range_to_grid_range(name, self.id) body = { "requests": [ { "addProtectedRange": { "protectedRange": { "range": grid_range, "description": description, "warningOnly": warning_only, "requestingUserCanEdit": requesting_user_can_edit, "editors": None if warning_only else { "users": editor_users_emails, "groups": editor_groups_emails, }, } } } ] } return self.client.batch_update(self.spreadsheet_id, body) def delete_protected_range(self, id: str) -> JSONResponse: """Delete protected range identified by the ID ``id``. To retrieve the ID of a protected range use the following method to list them all: :func:`~gspread.Spreadsheet.list_protected_ranges` """ body = { "requests": [ { "deleteProtectedRange": { "protectedRangeId": id, } } ] } return self.client.batch_update(self.spreadsheet_id, body) def delete_dimension( self, dimension: Dimension, start_index: int, end_index: Optional[int] = None ) -> JSONResponse: """Deletes multi rows from the worksheet at the specified index. :param dimension: A dimension to delete. ``Dimension.rows`` or ``Dimension.cols``. :type dimension: :class:`~gspread.utils.Dimension` :param int start_index: Index of a first row for deletion. :param int end_index: Index of a last row for deletion. When ``end_index`` is not specified this method only deletes a single row at ``start_index``. """ if end_index is None: end_index = start_index body = { "requests": [ { "deleteDimension": { "range": { "sheetId": self.id, "dimension": dimension, "startIndex": start_index - 1, "endIndex": end_index, } } } ] } res = self.client.batch_update(self.spreadsheet_id, body) if end_index is None: end_index = start_index num_deleted = end_index - start_index + 1 if dimension == Dimension.rows: self._properties["gridProperties"]["rowCount"] -= num_deleted elif dimension == Dimension.cols: self._properties["gridProperties"]["columnCount"] -= num_deleted return res def delete_rows( self, start_index: int, end_index: Optional[int] = None ) -> JSONResponse: """Deletes multiple rows from the worksheet at the specified index. :param int start_index: Index of a first row for deletion. :param int end_index: Index of a last row for deletion. When end_index is not specified this method only deletes a single row at ``start_index``. Example:: # Delete rows 5 to 10 (inclusive) worksheet.delete_rows(5, 10) # Delete only the second row worksheet.delete_rows(2) """ return self.delete_dimension(Dimension.rows, start_index, end_index) def delete_columns( self, start_index: int, end_index: Optional[int] = None ) -> JSONResponse: """Deletes multiple columns from the worksheet at the specified index. :param int start_index: Index of a first column for deletion. :param int end_index: Index of a last column for deletion. When end_index is not specified this method only deletes a single column at ``start_index``. """ return self.delete_dimension(Dimension.cols, start_index, end_index) def clear(self) -> JSONResponse: """Clears all cells in the worksheet.""" return self.client.values_clear( self.spreadsheet_id, absolute_range_name(self.title) ) def batch_clear(self, ranges: Sequence[str]) -> JSONResponse: """Clears multiple ranges of cells with 1 API call. `Batch Clear`_ .. _Batch Clear: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchClear Examples:: worksheet.batch_clear(['A1:B1','my_range']) # Note: named ranges are defined in the scope of # a spreadsheet, so even if `my_range` does not belong to # this sheet it is still updated .. versionadded:: 3.8.0 """ ranges = [absolute_range_name(self.title, rng) for rng in ranges] body = {"ranges": ranges} response = self.client.values_batch_clear(self.spreadsheet_id, body=body) return response def _finder( self, func: Callable[[Callable[[Cell], bool], Iterable[Cell]], Iterator[Cell]], query: Union[str, re.Pattern], case_sensitive: bool, in_row: Optional[int] = None, in_column: Optional[int] = None, ) -> Iterator[Cell]: data = self.client.values_get( self.spreadsheet_id, absolute_range_name(self.title) ) try: values = fill_gaps(data["values"]) except KeyError: values = [] cells = self._list_cells(values, in_row, in_column) if isinstance(query, str): str_query = query def match(x: Cell) -> bool: if case_sensitive or x.value is None: return x.value == str_query else: return x.value.casefold() == str_query.casefold() elif isinstance(query, re.Pattern): re_query = query def match(x: Cell) -> bool: return re_query.search(x.value) is not None else: raise TypeError( "query must be of type: 'str' or 're.Pattern' (obtained from re.compile())" ) return func(match, cells) def _list_cells( self, values: Sequence[Sequence[Union[str, int, float]]], in_row: Optional[int] = None, in_column: Optional[int] = None, ) -> List[Cell]: """Returns a list of ``Cell`` instances scoped by optional ``in_row``` or ``in_column`` values (both one-based). """ if in_row is not None and in_column is not None: raise TypeError("Either 'in_row' or 'in_column' should be specified.") if in_column is not None: return [ Cell(row=i + 1, col=in_column, value=str(row[in_column - 1])) for i, row in enumerate(values) ] elif in_row is not None: return [ Cell(row=in_row, col=j + 1, value=str(value)) for j, value in enumerate(values[in_row - 1]) ] else: return [ Cell(row=i + 1, col=j + 1, value=str(value)) for i, row in enumerate(values) for j, value in enumerate(row) ] def find( self, query: Union[str, re.Pattern], in_row: Optional[int] = None, in_column: Optional[int] = None, case_sensitive: bool = True, ) -> Optional[Cell]: """Finds the first cell matching the query. :param query: A literal string to match or compiled regular expression. :type query: str, :py:class:`re.RegexObject` :param int in_row: (optional) One-based row number to scope the search. :param int in_column: (optional) One-based column number to scope the search. :param bool case_sensitive: (optional) comparison is case sensitive if set to True, case insensitive otherwise. Default is True. Does not apply to regular expressions. :returns: the first matching cell or None otherwise :rtype: :class:`gspread.cell.Cell` """ try: return next(self._finder(filter, query, case_sensitive, in_row, in_column)) except StopIteration: return None def findall( self, query: Union[str, re.Pattern], in_row: Optional[int] = None, in_column: Optional[int] = None, case_sensitive: bool = True, ) -> List[Cell]: """Finds all cells matching the query. Returns a list of :class:`gspread.cell.Cell`. :param query: A literal string to match or compiled regular expression. :type query: str, :py:class:`re.RegexObject` :param int in_row: (optional) One-based row number to scope the search. :param int in_column: (optional) One-based column number to scope the search. :param bool case_sensitive: (optional) comparison is case sensitive if set to True, case insensitive otherwise. Default is True. Does not apply to regular expressions. :returns: the list of all matching cells or empty list otherwise :rtype: list """ return [ elem for elem in self._finder(filter, query, case_sensitive, in_row, in_column) ] def freeze( self, rows: Optional[int] = None, cols: Optional[int] = None ) -> JSONResponse: """Freeze rows and/or columns on the worksheet. :param rows: Number of rows to freeze. :param cols: Number of columns to freeze. """ grid_properties = {} if rows is not None: grid_properties["frozenRowCount"] = rows if cols is not None: grid_properties["frozenColumnCount"] = cols if not grid_properties: raise TypeError("Either 'rows' or 'cols' should be specified.") fields = ",".join("gridProperties/%s" % p for p in grid_properties.keys()) body = { "requests": [ { "updateSheetProperties": { "properties": { "sheetId": self.id, "gridProperties": grid_properties, }, "fields": fields, } } ] } res = self.client.batch_update(self.spreadsheet_id, body) if rows is not None: self._properties["gridProperties"]["frozenRowCount"] = rows if cols is not None: self._properties["gridProperties"]["frozenColumnCount"] = cols return res @cast_to_a1_notation def set_basic_filter(self, name: Optional[str] = None): """Add a basic filter to the worksheet. If a range or boundaries are passed, the filter will be limited to the given range. :param str name: A string with range value in A1 notation, e.g. ``A1:A5``. Alternatively, you may specify numeric boundaries. All values index from 1 (one): :param int first_row: First row number :param int first_col: First column number :param int last_row: Last row number :param int last_col: Last column number .. versionadded:: 3.4 """ grid_range = ( a1_range_to_grid_range(name, self.id) if name is not None else {"sheetId": self.id} ) body = {"requests": [{"setBasicFilter": {"filter": {"range": grid_range}}}]} return self.client.batch_update(self.spreadsheet_id, body) def clear_basic_filter(self) -> JSONResponse: """Remove the basic filter from a worksheet. .. versionadded:: 3.4 """ body = { "requests": [ { "clearBasicFilter": { "sheetId": self.id, } } ] } return self.client.batch_update(self.spreadsheet_id, body) @classmethod def _duplicate( cls, client: HTTPClient, spreadsheet_id: str, sheet_id: int, spreadsheet: Any, insert_sheet_index: Optional[int] = None, new_sheet_id: Optional[int] = None, new_sheet_name: Optional[str] = None, ) -> "Worksheet": """Class method to duplicate a :class:`gspread.worksheet.Worksheet`. :param Session client: The HTTP client used for the HTTP request :param str spreadsheet_id: The spreadsheet ID (used for the HTTP request) :param int sheet_id: The original sheet ID :param int insert_sheet_index: (optional) The zero-based index where the new sheet should be inserted. The index of all sheets after this are incremented. :param int new_sheet_id: (optional) The ID of the new sheet. If not set, an ID is chosen. If set, the ID must not conflict with any existing sheet ID. If set, it must be non-negative. :param str new_sheet_name: (optional) The name of the new sheet. If empty, a new name is chosen for you. :returns: a newly created :class:`gspread.worksheet.Worksheet`. .. note:: This is a class method in order for the spreadsheet class to use it without an instance of a Worksheet object """ body = { "requests": [ { "duplicateSheet": { "sourceSheetId": sheet_id, "insertSheetIndex": insert_sheet_index, "newSheetId": new_sheet_id, "newSheetName": new_sheet_name, } } ] } data = client.batch_update(spreadsheet_id, body) properties = data["replies"][0]["duplicateSheet"]["properties"] return Worksheet(spreadsheet, properties, spreadsheet_id, client) def duplicate( self, insert_sheet_index: Optional[int] = None, new_sheet_id: Optional[int] = None, new_sheet_name: Optional[str] = None, ) -> "Worksheet": """Duplicate the sheet. :param int insert_sheet_index: (optional) The zero-based index where the new sheet should be inserted. The index of all sheets after this are incremented. :param int new_sheet_id: (optional) The ID of the new sheet. If not set, an ID is chosen. If set, the ID must not conflict with any existing sheet ID. If set, it must be non-negative. :param str new_sheet_name: (optional) The name of the new sheet. If empty, a new name is chosen for you. :returns: a newly created :class:`gspread.worksheet.Worksheet`. .. versionadded:: 3.1 """ return Worksheet._duplicate( self.client, self.spreadsheet_id, self.id, self.spreadsheet, insert_sheet_index=insert_sheet_index, new_sheet_id=new_sheet_id, new_sheet_name=new_sheet_name, ) def copy_to( self, destination_spreadsheet_id: str, ) -> JSONResponse: """Copies this sheet to another spreadsheet. :param str spreadsheet_id: The ID of the spreadsheet to copy the sheet to. :returns: a dict with the response containing information about the newly created sheet. :rtype: dict """ return self.client.spreadsheets_sheets_copy_to( self.spreadsheet_id, self.id, destination_spreadsheet_id ) @cast_to_a1_notation def merge_cells(self, name: str, merge_type: str = MergeType.merge_all): """Merge cells. :param str name: Range name in A1 notation, e.g. 'A1:A5'. :param merge_type: (optional) one of ``MergeType.merge_all``, ``MergeType.merge_columns``, or ``MergeType.merge_rows``. Defaults to ``MergeType.merge_all``. See `MergeType`_ in the Sheets API reference. :type merge_type: :namedtuple:`~gspread.utils.MergeType` Alternatively, you may specify numeric boundaries. All values index from 1 (one): :param int first_row: First row number :param int first_col: First column number :param int last_row: Last row number :param int last_col: Last column number :returns: the response body from the request :rtype: dict .. _MergeType: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#MergeType """ grid_range = a1_range_to_grid_range(name, self.id) body = { "requests": [{"mergeCells": {"mergeType": merge_type, "range": grid_range}}] } return self.client.batch_update(self.spreadsheet_id, body) @cast_to_a1_notation def unmerge_cells(self, name: str) -> JSONResponse: """Unmerge cells. Unmerge previously merged cells. :param str name: Range name in A1 notation, e.g. 'A1:A5'. Alternatively, you may specify numeric boundaries. All values index from 1 (one): :param int first_row: First row number :param int first_col: First column number :param int last_row: Last row number :param int last_col: Last column number :returns: the response body from the request :rtype: dict """ grid_range = a1_range_to_grid_range(name, self.id) body = { "requests": [ { "unmergeCells": { "range": grid_range, }, }, ] } return self.client.batch_update(self.spreadsheet_id, body) def get_note(self, cell: str) -> str: """Get the content of the note located at `cell`, or the empty string if the cell does not have a note. :param str cell: A string with cell coordinates in A1 notation, e.g. 'D7'. """ absolute_cell = absolute_range_name(self.title, cell) params: ParamsType = { "ranges": absolute_cell, "fields": "sheets/data/rowData/values/note", } res = self.client.spreadsheets_get(self.spreadsheet_id, params) try: note = res["sheets"][0]["data"][0]["rowData"][0]["values"][0]["note"] except (IndexError, KeyError): note = "" return note def update_notes(self, notes: Mapping[str, str]) -> None: """update multiple notes. The notes are attached to a certain cell. :param notes dict: A dict of notes with their cells coordinates and respective content dict format is: * key: the cell coordinates as A1 range format * value: the string content of the cell Example:: { "D7": "Please read my notes", "GH42": "this one is too far", } .. versionadded:: 5.9 """ # No need to type lower than the sequence, it's internal only body: MutableMapping[str, List[Any]] = {"requests": []} for range, content in notes.items(): if not isinstance(content, str): raise TypeError( "Only string allowed as content for a note: '{} - {}'".format( range, content ) ) req = { "updateCells": { "range": a1_range_to_grid_range(range, self.id), "fields": "note", "rows": [ { "values": [ { "note": content, }, ], }, ], }, } body["requests"].append(req) self.client.batch_update(self.spreadsheet_id, body) @cast_to_a1_notation def update_note(self, cell: str, content: str) -> None: """Update the content of the note located at `cell`. :param str cell: A string with cell coordinates in A1 notation, e.g. 'D7'. :param str note: The text note to insert. .. versionadded:: 3.7 """ self.update_notes({cell: content}) @cast_to_a1_notation def insert_note(self, cell: str, content: str) -> None: """Insert a note. The note is attached to a certain cell. :param str cell: A string with cell coordinates in A1 notation, e.g. 'D7'. :param str content: The text note to insert. Alternatively, you may specify numeric boundaries. All values index from 1 (one): :param int first_row: First row number :param int first_col: First column number :param int last_row: Last row number :param int last_col: Last column number .. versionadded:: 3.7 """ self.update_notes({cell: content}) def insert_notes(self, notes: Mapping[str, str]) -> None: """insert multiple notes. The notes are attached to a certain cell. :param notes dict: A dict of notes with their cells coordinates and respective content dict format is: * key: the cell coordinates as A1 range format * value: the string content of the cell Example:: { "D7": "Please read my notes", "GH42": "this one is too far", } .. versionadded:: 5.9 """ self.update_notes(notes) def clear_notes(self, ranges: Iterable[str]) -> None: """Clear all notes located at the at the coordinates pointed to by ``ranges``. :param ranges list: List of A1 coordinates where to clear the notes. e.g. ``["A1", "GH42", "D7"]`` """ notes = {range: "" for range in ranges} self.update_notes(notes) @cast_to_a1_notation def clear_note(self, cell: str) -> None: """Clear a note. The note is attached to a certain cell. :param str cell: A string with cell coordinates in A1 notation, e.g. 'D7'. Alternatively, you may specify numeric boundaries. All values index from 1 (one): :param int first_row: First row number :param int first_col: First column number :param int last_row: Last row number :param int last_col: Last column number .. versionadded:: 3.7 """ # set the note to <empty string> will clear it self.update_notes({cell: ""}) @cast_to_a1_notation def define_named_range(self, name: str, range_name: str) -> JSONResponse: """ :param str name: A string with range value in A1 notation, e.g. 'A1:A5'. Alternatively, you may specify numeric boundaries. All values index from 1 (one): :param int first_row: First row number :param int first_col: First column number :param int last_row: Last row number :param int last_col: Last column number :param range_name: The name to assign to the range of cells :returns: the response body from the request :rtype: dict """ body = { "requests": [ { "addNamedRange": { "namedRange": { "name": range_name, "range": a1_range_to_grid_range(name, self.id), } } } ] } return self.client.batch_update(self.spreadsheet_id, body) def delete_named_range(self, named_range_id: str) -> JSONResponse: """ :param str named_range_id: The ID of the named range to delete. Can be obtained with Spreadsheet.list_named_ranges() :returns: the response body from the request :rtype: dict """ body = { "requests": [ { "deleteNamedRange": { "namedRangeId": named_range_id, } } ] } return self.client.batch_update(self.spreadsheet_id, body) def _add_dimension_group( self, start: int, end: int, dimension: Dimension ) -> JSONResponse: """ update this sheet by grouping 'dimension' :param int start: The start (inclusive) of the group :param int end: The end (exclusive) of the grou :param str dimension: The dimension to group, can be one of ``ROWS`` or ``COLUMNS``. :type diension: :class:`~gspread.utils.Dimension` """ body = { "requests": [ { "addDimensionGroup": { "range": { "sheetId": self.id, "dimension": dimension, "startIndex": start, "endIndex": end, }, } } ] } return self.client.batch_update(self.spreadsheet_id, body) def add_dimension_group_columns(self, start: int, end: int) -> JSONResponse: """ Group columns in order to hide them in the UI. .. note:: API behavior with nested groups and non-matching ``[start:end)`` range can be found here: `Add Dimension Group Request`_ .. _Add Dimension Group Request: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#AddDimensionGroupRequest :param int start: The start (inclusive) of the group :param int end: The end (exclusive) of the group """ return self._add_dimension_group(start, end, Dimension.cols) def add_dimension_group_rows(self, start: int, end: int) -> JSONResponse: """ Group rows in order to hide them in the UI. .. note:: API behavior with nested groups and non-matching ``[start:end)`` range can be found here `Add Dimension Group Request`_ :param int start: The start (inclusive) of the group :param int end: The end (exclusive) of the group """ return self._add_dimension_group(start, end, Dimension.rows) def _delete_dimension_group( self, start: int, end: int, dimension: Dimension ) -> JSONResponse: """delete a dimension group in this sheet""" body = { "requests": [ { "deleteDimensionGroup": { "range": { "sheetId": self.id, "dimension": dimension, "startIndex": start, "endIndex": end, } } } ] } return self.client.batch_update(self.spreadsheet_id, body) def delete_dimension_group_columns(self, start: int, end: int) -> JSONResponse: """ Remove the grouping of a set of columns. .. note:: API behavior with nested groups and non-matching ``[start:end)`` range can be found here `Delete Dimension Group Request`_ .. _Delete Dimension Group Request: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#DeleteDimensionGroupRequest :param int start: The start (inclusive) of the group :param int end: The end (exclusive) of the group """ return self._delete_dimension_group(start, end, Dimension.cols) def delete_dimension_group_rows(self, start: int, end: int) -> JSONResponse: """ Remove the grouping of a set of rows. .. note:: API behavior with nested groups and non-matching ``[start:end)`` range can be found here `Delete Dimension Group Request`_ :param int start: The start (inclusive) of the group :param int end: The end (exclusive) of the group """ return self._delete_dimension_group(start, end, Dimension.rows) def list_dimension_group_columns(self) -> List[JSONResponse]: """ List all the grouped columns in this worksheet. :returns: list of the grouped columns :rtype: list """ return self._get_sheet_property("columnGroups", []) def list_dimension_group_rows(self) -> List[JSONResponse]: """ List all the grouped rows in this worksheet. :returns: list of the grouped rows :rtype: list """ return self._get_sheet_property("rowGroups", []) def _hide_dimension( self, start: int, end: int, dimension: Dimension ) -> JSONResponse: """ Update this sheet by hiding the given 'dimension' Index starts from 0. :param int start: The (inclusive) start of the dimension to hide :param int end: The (exclusive) end of the dimension to hide :param str dimension: The dimension to hide, can be one of ``ROWS`` or ``COLUMNS``. :type diension: :class:`~gspread.utils.Dimension` """ body = { "requests": [ { "updateDimensionProperties": { "range": { "sheetId": self.id, "dimension": dimension, "startIndex": start, "endIndex": end, }, "properties": { "hiddenByUser": True, }, "fields": "hiddenByUser", } } ] } return self.client.batch_update(self.spreadsheet_id, body) def hide_columns(self, start: int, end: int) -> JSONResponse: """ Explicitly hide the given column index range. Index starts from 0. :param int start: The (inclusive) starting column to hide :param int end: The (exclusive) end column to hide """ return self._hide_dimension(start, end, Dimension.cols) def hide_rows(self, start: int, end: int) -> JSONResponse: """ Explicitly hide the given row index range. Index starts from 0. :param int start: The (inclusive) starting row to hide :param int end: The (exclusive) end row to hide """ return self._hide_dimension(start, end, Dimension.rows) def _unhide_dimension( self, start: int, end: int, dimension: Dimension ) -> JSONResponse: """ Update this sheet by unhiding the given 'dimension' Index starts from 0. :param int start: The (inclusive) start of the dimension to unhide :param int end: The (inclusive) end of the dimension to unhide :param str dimension: The dimension to hide, can be one of ``ROWS`` or ``COLUMNS``. :type dimension: :class:`~gspread.utils.Dimension` """ body = { "requests": [ { "updateDimensionProperties": { "range": { "sheetId": self.id, "dimension": dimension, "startIndex": start, "endIndex": end, }, "properties": { "hiddenByUser": False, }, "fields": "hiddenByUser", } } ] } return self.client.batch_update(self.spreadsheet_id, body) def unhide_columns(self, start: int, end: int) -> JSONResponse: """ Explicitly unhide the given column index range. Index start from 0. :param int start: The (inclusive) starting column to hide :param int end: The (exclusive) end column to hide """ return self._unhide_dimension(start, end, Dimension.cols) def unhide_rows(self, start: int, end: int) -> JSONResponse: """ Explicitly unhide the given row index range. Index start from 0. :param int start: The (inclusive) starting row to hide :param int end: The (exclusive) end row to hide """ return self._unhide_dimension(start, end, Dimension.rows) def _set_hidden_flag(self, hidden: bool) -> JSONResponse: """Send the appropriate request to hide/show the current worksheet""" body = { "requests": [ { "updateSheetProperties": { "properties": { "sheetId": self.id, "hidden": hidden, }, "fields": "hidden", } } ] } res = self.client.batch_update(self.spreadsheet_id, body) self._properties["hidden"] = hidden return res def hide(self) -> JSONResponse: """Hides the current worksheet from the UI.""" return self._set_hidden_flag(True) def show(self) -> JSONResponse: """Show the current worksheet in the UI.""" return self._set_hidden_flag(False) def _set_gridlines_hidden_flag(self, hidden: bool) -> JSONResponse: """Hide/show gridlines on the current worksheet""" body = { "requests": [ { "updateSheetProperties": { "properties": { "sheetId": self.id, "gridProperties": { "hideGridlines": hidden, }, }, "fields": "gridProperties.hideGridlines", } } ] } res = self.client.batch_update(self.spreadsheet_id, body) self._properties["gridProperties"]["hideGridlines"] = hidden return res def hide_gridlines(self) -> JSONResponse: """Hide gridlines on the current worksheet""" return self._set_gridlines_hidden_flag(True) def show_gridlines(self) -> JSONResponse: """Show gridlines on the current worksheet""" return self._set_gridlines_hidden_flag(False) def copy_range( self, source: str, dest: str, paste_type: PasteType = PasteType.normal, paste_orientation: PasteOrientation = PasteOrientation.normal, ) -> JSONResponse: """Copies a range of data from source to dest .. note:: ``paste_type`` values are explained here: `Paste Types`_ .. _Paste Types: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#pastetype :param str source: The A1 notation of the source range to copy :param str dest: The A1 notation of the destination where to paste the data Can be the A1 notation of the top left corner where the range must be paste ex: G16, or a complete range notation ex: G16:I20. The dimensions of the destination range is not checked and has no effect, if the destination range does not match the source range dimension, the entire source range is copies anyway. :param paste_type: the paste type to apply. Many paste type are available from the Sheet API, see above note for detailed values for all values and their effects. Defaults to ``PasteType.normal`` :type paste_type: :class:`~gspread.utils.PasteType` :param paste_orientation: The paste orient to apply. Possible values are: ``normal`` to keep the same orientation, ``transpose`` where all rows become columns and vice versa. :type paste_orientation: :class:`~gspread.utils.PasteOrientation` """ body = { "requests": [ { "copyPaste": { "source": a1_range_to_grid_range(source, self.id), "destination": a1_range_to_grid_range(dest, self.id), "pasteType": paste_type, "pasteOrientation": paste_orientation, } } ] } return self.client.batch_update(self.spreadsheet_id, body) def cut_range( self, source: str, dest: str, paste_type: PasteType = PasteType.normal, ) -> JSONResponse: """Moves a range of data form source to dest .. note:: ``paste_type`` values are explained here: `Paste Types`_ .. _Paste Types: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#pastetype :param str source: The A1 notation of the source range to move :param str dest: The A1 notation of the destination where to paste the data **it must be a single cell** in the A1 notation. ex: G16 :param paste_type: the paste type to apply. Many paste type are available from the Sheet API, see above note for detailed values for all values and their effects. Defaults to ``PasteType.normal`` :type paste_type: :class:`~gspread.utils.PasteType` """ # in the cut/paste request, the destination object # is a `gridCoordinate` and not a `gridRang` # it has different object keys grid_dest = a1_range_to_grid_range(dest, self.id) body = { "requests": [ { "cutPaste": { "source": a1_range_to_grid_range(source, self.id), "destination": { "sheetId": grid_dest["sheetId"], "rowIndex": grid_dest["startRowIndex"], "columnIndex": grid_dest["startColumnIndex"], }, "pasteType": paste_type, } } ] } return self.client.batch_update(self.spreadsheet_id, body)
(spreadsheet: 'Spreadsheet', properties: MutableMapping[str, Any], spreadsheet_id: Optional[str] = None, client: Optional[gspread.http_client.HTTPClient] = None)
708,215
gspread.worksheet
__init__
null
def __init__( self, spreadsheet: "Spreadsheet", properties: MutableMapping[str, Any], spreadsheet_id: Optional[str] = None, client: Optional[HTTPClient] = None, ): # This object is not intended to be created manually # only using gspread code like: spreadsheet.get_worksheet(0) # keep it backward compatible signarure but raise with explicit message # in case of missing new attributes if spreadsheet_id is None or "": raise RuntimeError( """Missing spreadsheet_id parameter, it must be provided with a valid spreadsheet ID. Please allocate new Worksheet object using method like: spreadsheet.get_worksheet(0) """ ) if client is None or not isinstance(client, HTTPClient): raise RuntimeError( """Missing HTTP Client, it must be provided with a valid instance of type gspread.http_client.HTTPClient . Please allocate new Worksheet object using method like: spreadsheet.get_worksheet(0) """ ) self.spreadsheet_id = spreadsheet_id self.client = client self._properties = properties # kept for backward compatibility - publicly available # do not use if possible. self._spreadsheet = spreadsheet
(self, spreadsheet: 'Spreadsheet', properties: MutableMapping[str, Any], spreadsheet_id: Optional[str] = None, client: Optional[gspread.http_client.HTTPClient] = None)
708,216
gspread.worksheet
__repr__
null
def __repr__(self) -> str: return "<{} {} id:{}>".format( self.__class__.__name__, repr(self.title), self.id, )
(self) -> str
708,217
gspread.worksheet
_add_dimension_group
update this sheet by grouping 'dimension' :param int start: The start (inclusive) of the group :param int end: The end (exclusive) of the grou :param str dimension: The dimension to group, can be one of ``ROWS`` or ``COLUMNS``. :type diension: :class:`~gspread.utils.Dimension`
def _add_dimension_group( self, start: int, end: int, dimension: Dimension ) -> JSONResponse: """ update this sheet by grouping 'dimension' :param int start: The start (inclusive) of the group :param int end: The end (exclusive) of the grou :param str dimension: The dimension to group, can be one of ``ROWS`` or ``COLUMNS``. :type diension: :class:`~gspread.utils.Dimension` """ body = { "requests": [ { "addDimensionGroup": { "range": { "sheetId": self.id, "dimension": dimension, "startIndex": start, "endIndex": end, }, } } ] } return self.client.batch_update(self.spreadsheet_id, body)
(self, start: int, end: int, dimension: gspread.utils.Dimension) -> MutableMapping[str, Any]
708,218
gspread.worksheet
_auto_resize
Updates the size of rows or columns in the worksheet. Index start from 0 :param start_index: The index (inclusive) to begin resizing :param end_index: The index (exclusive) to finish resizing :param dimension: Specifies whether to resize the row or column :type major_dimension: :class:`~gspread.utils.Dimension` .. versionadded:: 5.3.3
def _auto_resize( self, start_index: int, end_index: int, dimension: Dimension ) -> JSONResponse: """Updates the size of rows or columns in the worksheet. Index start from 0 :param start_index: The index (inclusive) to begin resizing :param end_index: The index (exclusive) to finish resizing :param dimension: Specifies whether to resize the row or column :type major_dimension: :class:`~gspread.utils.Dimension` .. versionadded:: 5.3.3 """ body = { "requests": [ { "autoResizeDimensions": { "dimensions": { "sheetId": self.id, "dimension": dimension, "startIndex": start_index, "endIndex": end_index, } } } ] } return self.client.batch_update(self.spreadsheet_id, body)
(self, start_index: int, end_index: int, dimension: gspread.utils.Dimension) -> MutableMapping[str, Any]
708,219
gspread.worksheet
_delete_dimension_group
delete a dimension group in this sheet
def _delete_dimension_group( self, start: int, end: int, dimension: Dimension ) -> JSONResponse: """delete a dimension group in this sheet""" body = { "requests": [ { "deleteDimensionGroup": { "range": { "sheetId": self.id, "dimension": dimension, "startIndex": start, "endIndex": end, } } } ] } return self.client.batch_update(self.spreadsheet_id, body)
(self, start: int, end: int, dimension: gspread.utils.Dimension) -> MutableMapping[str, Any]
708,220
gspread.worksheet
_finder
null
def _finder( self, func: Callable[[Callable[[Cell], bool], Iterable[Cell]], Iterator[Cell]], query: Union[str, re.Pattern], case_sensitive: bool, in_row: Optional[int] = None, in_column: Optional[int] = None, ) -> Iterator[Cell]: data = self.client.values_get( self.spreadsheet_id, absolute_range_name(self.title) ) try: values = fill_gaps(data["values"]) except KeyError: values = [] cells = self._list_cells(values, in_row, in_column) if isinstance(query, str): str_query = query def match(x: Cell) -> bool: if case_sensitive or x.value is None: return x.value == str_query else: return x.value.casefold() == str_query.casefold() elif isinstance(query, re.Pattern): re_query = query def match(x: Cell) -> bool: return re_query.search(x.value) is not None else: raise TypeError( "query must be of type: 'str' or 're.Pattern' (obtained from re.compile())" ) return func(match, cells)
(self, func: Callable[[Callable[[gspread.cell.Cell], bool], Iterable[gspread.cell.Cell]], Iterator[gspread.cell.Cell]], query: Union[str, re.Pattern], case_sensitive: bool, in_row: Optional[int] = None, in_column: Optional[int] = None) -> Iterator[gspread.cell.Cell]
708,221
gspread.worksheet
_get_sheet_property
return a property of this worksheet or default value if not found
def _get_sheet_property(self, property: str, default_value: Optional[T]) -> T: """return a property of this worksheet or default value if not found""" meta = self.client.fetch_sheet_metadata(self.spreadsheet_id) sheet = finditem( lambda x: x["properties"]["sheetId"] == self.id, meta["sheets"] ) return sheet.get(property, default_value)
(self, property: str, default_value: Optional[~T]) -> ~T
708,222
gspread.worksheet
_hide_dimension
Update this sheet by hiding the given 'dimension' Index starts from 0. :param int start: The (inclusive) start of the dimension to hide :param int end: The (exclusive) end of the dimension to hide :param str dimension: The dimension to hide, can be one of ``ROWS`` or ``COLUMNS``. :type diension: :class:`~gspread.utils.Dimension`
def _hide_dimension( self, start: int, end: int, dimension: Dimension ) -> JSONResponse: """ Update this sheet by hiding the given 'dimension' Index starts from 0. :param int start: The (inclusive) start of the dimension to hide :param int end: The (exclusive) end of the dimension to hide :param str dimension: The dimension to hide, can be one of ``ROWS`` or ``COLUMNS``. :type diension: :class:`~gspread.utils.Dimension` """ body = { "requests": [ { "updateDimensionProperties": { "range": { "sheetId": self.id, "dimension": dimension, "startIndex": start, "endIndex": end, }, "properties": { "hiddenByUser": True, }, "fields": "hiddenByUser", } } ] } return self.client.batch_update(self.spreadsheet_id, body)
(self, start: int, end: int, dimension: gspread.utils.Dimension) -> MutableMapping[str, Any]
708,223
gspread.worksheet
_list_cells
Returns a list of ``Cell`` instances scoped by optional ``in_row``` or ``in_column`` values (both one-based).
def _list_cells( self, values: Sequence[Sequence[Union[str, int, float]]], in_row: Optional[int] = None, in_column: Optional[int] = None, ) -> List[Cell]: """Returns a list of ``Cell`` instances scoped by optional ``in_row``` or ``in_column`` values (both one-based). """ if in_row is not None and in_column is not None: raise TypeError("Either 'in_row' or 'in_column' should be specified.") if in_column is not None: return [ Cell(row=i + 1, col=in_column, value=str(row[in_column - 1])) for i, row in enumerate(values) ] elif in_row is not None: return [ Cell(row=in_row, col=j + 1, value=str(value)) for j, value in enumerate(values[in_row - 1]) ] else: return [ Cell(row=i + 1, col=j + 1, value=str(value)) for i, row in enumerate(values) for j, value in enumerate(row) ]
(self, values: Sequence[Sequence[Union[str, int, float]]], in_row: Optional[int] = None, in_column: Optional[int] = None) -> List[gspread.cell.Cell]
708,224
gspread.worksheet
_set_gridlines_hidden_flag
Hide/show gridlines on the current worksheet
def _set_gridlines_hidden_flag(self, hidden: bool) -> JSONResponse: """Hide/show gridlines on the current worksheet""" body = { "requests": [ { "updateSheetProperties": { "properties": { "sheetId": self.id, "gridProperties": { "hideGridlines": hidden, }, }, "fields": "gridProperties.hideGridlines", } } ] } res = self.client.batch_update(self.spreadsheet_id, body) self._properties["gridProperties"]["hideGridlines"] = hidden return res
(self, hidden: bool) -> MutableMapping[str, Any]
708,225
gspread.worksheet
_set_hidden_flag
Send the appropriate request to hide/show the current worksheet
def _set_hidden_flag(self, hidden: bool) -> JSONResponse: """Send the appropriate request to hide/show the current worksheet""" body = { "requests": [ { "updateSheetProperties": { "properties": { "sheetId": self.id, "hidden": hidden, }, "fields": "hidden", } } ] } res = self.client.batch_update(self.spreadsheet_id, body) self._properties["hidden"] = hidden return res
(self, hidden: bool) -> MutableMapping[str, Any]
708,226
gspread.worksheet
_unhide_dimension
Update this sheet by unhiding the given 'dimension' Index starts from 0. :param int start: The (inclusive) start of the dimension to unhide :param int end: The (inclusive) end of the dimension to unhide :param str dimension: The dimension to hide, can be one of ``ROWS`` or ``COLUMNS``. :type dimension: :class:`~gspread.utils.Dimension`
def _unhide_dimension( self, start: int, end: int, dimension: Dimension ) -> JSONResponse: """ Update this sheet by unhiding the given 'dimension' Index starts from 0. :param int start: The (inclusive) start of the dimension to unhide :param int end: The (inclusive) end of the dimension to unhide :param str dimension: The dimension to hide, can be one of ``ROWS`` or ``COLUMNS``. :type dimension: :class:`~gspread.utils.Dimension` """ body = { "requests": [ { "updateDimensionProperties": { "range": { "sheetId": self.id, "dimension": dimension, "startIndex": start, "endIndex": end, }, "properties": { "hiddenByUser": False, }, "fields": "hiddenByUser", } } ] } return self.client.batch_update(self.spreadsheet_id, body)
(self, start: int, end: int, dimension: gspread.utils.Dimension) -> MutableMapping[str, Any]
708,227
gspread.worksheet
acell
Returns an instance of a :class:`gspread.cell.Cell`. :param label: Cell label in A1 notation Letter case is ignored. :type label: str :param value_render_option: (optional) Determines how values should be rendered in the output. See `ValueRenderOption`_ in the Sheets API. :type value_render_option: :class:`~gspread.utils.ValueRenderOption` .. _ValueRenderOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueRenderOption Example: >>> worksheet.acell('A1') <Cell R1C1 "I'm cell A1">
def acell( self, label: str, value_render_option: ValueRenderOption = ValueRenderOption.formatted, ) -> Cell: """Returns an instance of a :class:`gspread.cell.Cell`. :param label: Cell label in A1 notation Letter case is ignored. :type label: str :param value_render_option: (optional) Determines how values should be rendered in the output. See `ValueRenderOption`_ in the Sheets API. :type value_render_option: :class:`~gspread.utils.ValueRenderOption` .. _ValueRenderOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueRenderOption Example: >>> worksheet.acell('A1') <Cell R1C1 "I'm cell A1"> """ return self.cell( *(a1_to_rowcol(label)), value_render_option=value_render_option )
(self, label: str, value_render_option: gspread.utils.ValueRenderOption = <ValueRenderOption.formatted: 'FORMATTED_VALUE'>) -> gspread.cell.Cell
708,228
gspread.worksheet
add_cols
Adds columns to worksheet. :param cols: Number of new columns to add. :type cols: int
def add_cols(self, cols: int) -> None: """Adds columns to worksheet. :param cols: Number of new columns to add. :type cols: int """ self.resize(cols=self.col_count + cols)
(self, cols: int) -> NoneType
708,229
gspread.worksheet
add_dimension_group_columns
Group columns in order to hide them in the UI. .. note:: API behavior with nested groups and non-matching ``[start:end)`` range can be found here: `Add Dimension Group Request`_ .. _Add Dimension Group Request: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#AddDimensionGroupRequest :param int start: The start (inclusive) of the group :param int end: The end (exclusive) of the group
def add_dimension_group_columns(self, start: int, end: int) -> JSONResponse: """ Group columns in order to hide them in the UI. .. note:: API behavior with nested groups and non-matching ``[start:end)`` range can be found here: `Add Dimension Group Request`_ .. _Add Dimension Group Request: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#AddDimensionGroupRequest :param int start: The start (inclusive) of the group :param int end: The end (exclusive) of the group """ return self._add_dimension_group(start, end, Dimension.cols)
(self, start: int, end: int) -> MutableMapping[str, Any]
708,230
gspread.worksheet
add_dimension_group_rows
Group rows in order to hide them in the UI. .. note:: API behavior with nested groups and non-matching ``[start:end)`` range can be found here `Add Dimension Group Request`_ :param int start: The start (inclusive) of the group :param int end: The end (exclusive) of the group
def add_dimension_group_rows(self, start: int, end: int) -> JSONResponse: """ Group rows in order to hide them in the UI. .. note:: API behavior with nested groups and non-matching ``[start:end)`` range can be found here `Add Dimension Group Request`_ :param int start: The start (inclusive) of the group :param int end: The end (exclusive) of the group """ return self._add_dimension_group(start, end, Dimension.rows)
(self, start: int, end: int) -> MutableMapping[str, Any]