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,231
|
gspread.worksheet
|
add_protected_range
|
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``.
|
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)
|
(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) -> MutableMapping[str, Any]
|
708,232
|
gspread.worksheet
|
add_rows
|
Adds rows to worksheet.
:param rows: Number of new rows to add.
:type rows: int
|
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)
|
(self, rows: int) -> NoneType
|
708,233
|
gspread.worksheet
|
append_row
|
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
|
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,
)
|
(self, values: Sequence[Union[str, int, float]], value_input_option: gspread.utils.ValueInputOption = <ValueInputOption.raw: 'RAW'>, insert_data_option: Optional[gspread.utils.InsertDataOption] = None, table_range: Optional[str] = None, include_values_in_response: bool = False) -> MutableMapping[str, Any]
|
708,234
|
gspread.worksheet
|
append_rows
|
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
|
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
|
(self, values: Sequence[Sequence[Union[str, int, float]]], value_input_option: gspread.utils.ValueInputOption = <ValueInputOption.raw: 'RAW'>, insert_data_option: Optional[gspread.utils.InsertDataOption] = None, table_range: Optional[str] = None, include_values_in_response: Optional[bool] = None) -> MutableMapping[str, Any]
|
708,235
|
gspread.worksheet
|
batch_clear
|
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
|
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
|
(self, ranges: Sequence[str]) -> MutableMapping[str, Any]
|
708,236
|
gspread.worksheet
|
batch_format
|
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
|
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)
|
(self, formats: List[gspread.worksheet.CellFormat]) -> MutableMapping[str, Any]
|
708,237
|
gspread.worksheet
|
batch_get
|
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'])
|
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"]]
|
(self, ranges: Iterable[str], major_dimension: Optional[gspread.utils.Dimension] = None, value_render_option: Optional[gspread.utils.ValueRenderOption] = None, date_time_render_option: Optional[gspread.utils.DateTimeOption] = None) -> List[gspread.worksheet.ValueRange]
|
708,238
|
gspread.worksheet
|
batch_update
|
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
|
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
|
(self, data: Iterable[MutableMapping[str, Any]], raw: bool = True, value_input_option: Optional[gspread.utils.ValueInputOption] = None, include_values_in_response: Optional[bool] = None, response_value_render_option: Optional[gspread.utils.ValueRenderOption] = None, response_date_time_render_option: Optional[gspread.utils.DateTimeOption] = None) -> MutableMapping[str, Any]
|
708,239
|
gspread.worksheet
|
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`
|
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)
|
(self, row: int, col: int, value_render_option: gspread.utils.ValueRenderOption = <ValueRenderOption.formatted: 'FORMATTED_VALUE'>) -> gspread.cell.Cell
|
708,240
|
gspread.worksheet
|
clear
|
Clears all cells in the worksheet.
|
def clear(self) -> JSONResponse:
"""Clears all cells in the worksheet."""
return self.client.values_clear(
self.spreadsheet_id, absolute_range_name(self.title)
)
|
(self) -> MutableMapping[str, Any]
|
708,241
|
gspread.worksheet
|
clear_basic_filter
|
Remove the basic filter from a worksheet.
.. versionadded:: 3.4
|
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)
|
(self) -> MutableMapping[str, Any]
|
708,242
|
gspread.worksheet
|
clear_note
|
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
|
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)
|
(self, cell: str) -> NoneType
|
708,243
|
gspread.worksheet
|
clear_notes
|
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"]``
|
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)
|
(self, ranges: Iterable[str]) -> NoneType
|
708,244
|
gspread.worksheet
|
clear_tab_color
|
Clears the worksheet's tab color.
Use update_tab_color() to set the color.
|
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
|
(self) -> MutableMapping[str, Any]
|
708,245
|
gspread.worksheet
|
col_values
|
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
|
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 []
|
(self, col: int, value_render_option: gspread.utils.ValueRenderOption = <ValueRenderOption.formatted: 'FORMATTED_VALUE'>) -> List[Union[int, float, str, NoneType]]
|
708,246
|
gspread.worksheet
|
columns_auto_resize
|
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
|
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)
|
(self, start_column_index: int, end_column_index: int) -> MutableMapping[str, Any]
|
708,247
|
gspread.worksheet
|
copy_range
|
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`
|
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)
|
(self, source: str, dest: str, paste_type: gspread.utils.PasteType = <PasteType.normal: 'PASTE_NORMAL'>, paste_orientation: gspread.utils.PasteOrientation = <PasteOrientation.normal: 'NORMAL'>) -> MutableMapping[str, Any]
|
708,248
|
gspread.worksheet
|
copy_to
|
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
|
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
)
|
(self, destination_spreadsheet_id: str) -> MutableMapping[str, Any]
|
708,249
|
gspread.worksheet
|
cut_range
|
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`
|
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)
|
(self, source: str, dest: str, paste_type: gspread.utils.PasteType = <PasteType.normal: 'PASTE_NORMAL'>) -> MutableMapping[str, Any]
|
708,250
|
gspread.worksheet
|
define_named_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
:param range_name: The name to assign to the range of cells
:returns: the response body from the request
:rtype: dict
|
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)
|
(self, name: str, range_name: str) -> MutableMapping[str, Any]
|
708,251
|
gspread.worksheet
|
delete_columns
|
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``.
|
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)
|
(self, start_index: int, end_index: Optional[int] = None) -> MutableMapping[str, Any]
|
708,252
|
gspread.worksheet
|
delete_dimension
|
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``.
|
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
|
(self, dimension: gspread.utils.Dimension, start_index: int, end_index: Optional[int] = None) -> MutableMapping[str, Any]
|
708,253
|
gspread.worksheet
|
delete_dimension_group_columns
|
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
|
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)
|
(self, start: int, end: int) -> MutableMapping[str, Any]
|
708,254
|
gspread.worksheet
|
delete_dimension_group_rows
|
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
|
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)
|
(self, start: int, end: int) -> MutableMapping[str, Any]
|
708,255
|
gspread.worksheet
|
delete_named_range
|
: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
|
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)
|
(self, named_range_id: str) -> MutableMapping[str, Any]
|
708,256
|
gspread.worksheet
|
delete_protected_range
|
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`
|
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)
|
(self, id: str) -> MutableMapping[str, Any]
|
708,257
|
gspread.worksheet
|
delete_rows
|
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)
|
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)
|
(self, start_index: int, end_index: Optional[int] = None) -> MutableMapping[str, Any]
|
708,258
|
gspread.worksheet
|
duplicate
|
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
|
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,
)
|
(self, insert_sheet_index: Optional[int] = None, new_sheet_id: Optional[int] = None, new_sheet_name: Optional[str] = None) -> gspread.worksheet.Worksheet
|
708,259
|
gspread.worksheet
|
find
|
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`
|
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
|
(self, query: Union[str, re.Pattern], in_row: Optional[int] = None, in_column: Optional[int] = None, case_sensitive: bool = True) -> Optional[gspread.cell.Cell]
|
708,260
|
gspread.worksheet
|
findall
|
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
|
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)
]
|
(self, query: Union[str, re.Pattern], in_row: Optional[int] = None, in_column: Optional[int] = None, case_sensitive: bool = True) -> List[gspread.cell.Cell]
|
708,261
|
gspread.worksheet
|
format
|
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
|
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)
|
(self, ranges: Union[List[str], str], format: MutableMapping[str, Any]) -> MutableMapping[str, Any]
|
708,262
|
gspread.worksheet
|
freeze
|
Freeze rows and/or columns on the worksheet.
:param rows: Number of rows to freeze.
:param cols: Number of columns to freeze.
|
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
|
(self, rows: Optional[int] = None, cols: Optional[int] = None) -> MutableMapping[str, Any]
|
708,263
|
gspread.worksheet
|
get
|
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)
|
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")
|
(self, range_name: Optional[str] = None, major_dimension: Optional[gspread.utils.Dimension] = None, value_render_option: Optional[gspread.utils.ValueRenderOption] = None, date_time_render_option: Optional[gspread.utils.DateTimeOption] = None, combine_merged_cells: bool = False, maintain_size: bool = False, pad_values: bool = False, return_type: gspread.utils.GridRangeType = <GridRangeType.ValueRange: 'ValueRange'>) -> Union[gspread.worksheet.ValueRange, List[List[Any]]]
|
708,264
|
gspread.worksheet
|
get_all_cells
|
Returns a list of all `Cell` of the current sheet.
|
def get_all_cells(self) -> List[Cell]:
"""Returns a list of all `Cell` of the current sheet."""
return self.range()
|
(self) -> List[gspread.cell.Cell]
|
708,265
|
gspread.worksheet
|
get_all_records
|
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"}
]
|
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)
|
(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[str, int, float]]]
|
708,266
|
gspread.worksheet
|
get_all_values
|
Alias to :meth:`~gspread.worksheet.Worksheet.get_values`
|
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,
)
|
(self, range_name: Optional[str] = None, major_dimension: Optional[gspread.utils.Dimension] = None, value_render_option: Optional[gspread.utils.ValueRenderOption] = None, date_time_render_option: Optional[gspread.utils.DateTimeOption] = None, combine_merged_cells: bool = False, maintain_size: bool = False, pad_values: bool = True, return_type: gspread.utils.GridRangeType = <GridRangeType.ListOfLists: 'ListOfLists'>) -> List[List[~T]]
|
708,267
|
gspread.worksheet
|
get_note
|
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'.
|
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
|
(self, cell: str) -> str
|
708,268
|
gspread.worksheet
|
get_tab_color
|
Tab color style in hex format. String.
|
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)
|
(self) -> Optional[str]
|
708,269
|
gspread.worksheet
|
get_values
|
Alias for :meth:`~gspread.worksheet.Worksheet.get`...
with ``return_type`` set to ``List[List[Any]]``
and ``pad_values`` set to ``True``
(legacy method)
|
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,
)
|
(self, range_name: Optional[str] = None, major_dimension: Optional[gspread.utils.Dimension] = None, value_render_option: Optional[gspread.utils.ValueRenderOption] = None, date_time_render_option: Optional[gspread.utils.DateTimeOption] = None, combine_merged_cells: bool = False, maintain_size: bool = False, pad_values: bool = True, return_type: gspread.utils.GridRangeType = <GridRangeType.ListOfLists: 'ListOfLists'>) -> List[List[~T]]
|
708,270
|
gspread.worksheet
|
hide
|
Hides the current worksheet from the UI.
|
def hide(self) -> JSONResponse:
"""Hides the current worksheet from the UI."""
return self._set_hidden_flag(True)
|
(self) -> MutableMapping[str, Any]
|
708,271
|
gspread.worksheet
|
hide_columns
|
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
|
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)
|
(self, start: int, end: int) -> MutableMapping[str, Any]
|
708,272
|
gspread.worksheet
|
hide_gridlines
|
Hide gridlines on the current worksheet
|
def hide_gridlines(self) -> JSONResponse:
"""Hide gridlines on the current worksheet"""
return self._set_gridlines_hidden_flag(True)
|
(self) -> MutableMapping[str, Any]
|
708,273
|
gspread.worksheet
|
hide_rows
|
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
|
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)
|
(self, start: int, end: int) -> MutableMapping[str, Any]
|
708,274
|
gspread.worksheet
|
insert_cols
|
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.
|
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
|
(self, values: Sequence[Sequence[Union[str, int, float]]], col: int = 1, value_input_option: gspread.utils.ValueInputOption = <ValueInputOption.raw: 'RAW'>, inherit_from_before: bool = False) -> MutableMapping[str, Any]
|
708,275
|
gspread.worksheet
|
insert_note
|
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
|
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)
|
(self, cell: str, content: str) -> NoneType
|
708,276
|
gspread.worksheet
|
insert_notes
|
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
|
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)
|
(self, notes: Mapping[str, str]) -> NoneType
|
708,277
|
gspread.worksheet
|
insert_row
|
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
|
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,
)
|
(self, values: Sequence[Union[str, int, float]], index: int = 1, value_input_option: gspread.utils.ValueInputOption = <ValueInputOption.raw: 'RAW'>, inherit_from_before: bool = False) -> MutableMapping[str, Any]
|
708,278
|
gspread.worksheet
|
insert_rows
|
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.
|
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
|
(self, values: Sequence[Sequence[Union[str, int, float]]], row: int = 1, value_input_option: gspread.utils.ValueInputOption = <ValueInputOption.raw: 'RAW'>, inherit_from_before: bool = False) -> MutableMapping[str, Any]
|
708,279
|
gspread.worksheet
|
list_dimension_group_columns
|
List all the grouped columns in this worksheet.
:returns: list of the grouped columns
:rtype: list
|
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", [])
|
(self) -> List[MutableMapping[str, Any]]
|
708,280
|
gspread.worksheet
|
list_dimension_group_rows
|
List all the grouped rows in this worksheet.
:returns: list of the grouped rows
:rtype: list
|
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", [])
|
(self) -> List[MutableMapping[str, Any]]
|
708,281
|
gspread.worksheet
|
merge_cells
|
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
|
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)
|
(self, name: str, merge_type: str = <MergeType.merge_all: 'MERGE_ALL'>)
|
708,282
|
gspread.worksheet
|
range
|
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'>, ...]
|
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)
|
(self, name: str = '') -> List[gspread.cell.Cell]
|
708,283
|
gspread.worksheet
|
resize
|
Resizes the worksheet. Specify one of ``rows`` or ``cols``.
:param int rows: (optional) New number of rows.
:param int cols: (optional) New number columns.
|
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
|
(self, rows: Optional[int] = None, cols: Optional[int] = None) -> MutableMapping[str, Any]
|
708,284
|
gspread.worksheet
|
row_values
|
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`
|
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 []
|
(self, row: int, major_dimension: Optional[gspread.utils.Dimension] = None, value_render_option: Optional[gspread.utils.ValueRenderOption] = None, date_time_render_option: Optional[gspread.utils.DateTimeOption] = None) -> List[Union[int, float, str, NoneType]]
|
708,285
|
gspread.worksheet
|
rows_auto_resize
|
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
|
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)
|
(self, start_row_index: int, end_row_index: int) -> MutableMapping[str, Any]
|
708,286
|
gspread.worksheet
|
set_basic_filter
|
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
|
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)
|
(self, name: Optional[str] = None)
|
708,287
|
gspread.worksheet
|
show
|
Show the current worksheet in the UI.
|
def show(self) -> JSONResponse:
"""Show the current worksheet in the UI."""
return self._set_hidden_flag(False)
|
(self) -> MutableMapping[str, Any]
|
708,288
|
gspread.worksheet
|
show_gridlines
|
Show gridlines on the current worksheet
|
def show_gridlines(self) -> JSONResponse:
"""Show gridlines on the current worksheet"""
return self._set_gridlines_hidden_flag(False)
|
(self) -> MutableMapping[str, Any]
|
708,289
|
gspread.worksheet
|
sort
|
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
|
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
|
(self, *specs: Tuple[int, Literal['asc', 'des']], range: Optional[str] = None) -> MutableMapping[str, Any]
|
708,290
|
gspread.worksheet
|
unhide_columns
|
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
|
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)
|
(self, start: int, end: int) -> MutableMapping[str, Any]
|
708,291
|
gspread.worksheet
|
unhide_rows
|
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
|
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)
|
(self, start: int, end: int) -> MutableMapping[str, Any]
|
708,292
|
gspread.worksheet
|
unmerge_cells
|
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
|
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)
|
(self, name: str) -> MutableMapping[str, Any]
|
708,293
|
gspread.worksheet
|
update
|
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
|
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
|
(self, values: Iterable[Iterable[Any]], range_name: Optional[str] = None, raw: bool = True, major_dimension: Optional[gspread.utils.Dimension] = None, value_input_option: Optional[gspread.utils.ValueInputOption] = None, include_values_in_response: Optional[bool] = None, response_value_render_option: Optional[gspread.utils.ValueRenderOption] = None, response_date_time_render_option: Optional[gspread.utils.DateTimeOption] = None) -> MutableMapping[str, Any]
|
708,294
|
gspread.worksheet
|
update_acell
|
Updates the value of a cell.
:param str label: Cell label in A1 notation.
:param value: New value.
Example::
worksheet.update_acell('A1', '42')
|
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)
|
(self, label: str, value: Union[int, float, str]) -> MutableMapping[str, Any]
|
708,295
|
gspread.worksheet
|
update_cell
|
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')
|
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
|
(self, row: int, col: int, value: Union[int, float, str]) -> MutableMapping[str, Any]
|
708,296
|
gspread.worksheet
|
update_cells
|
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)
|
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
|
(self, cell_list: List[gspread.cell.Cell], value_input_option: gspread.utils.ValueInputOption = <ValueInputOption.raw: 'RAW'>) -> Mapping[str, Any]
|
708,297
|
gspread.worksheet
|
update_index
|
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
|
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
|
(self, index: int) -> MutableMapping[str, Any]
|
708,298
|
gspread.worksheet
|
update_note
|
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
|
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)
|
(self, cell: str, content: str) -> NoneType
|
708,299
|
gspread.worksheet
|
update_notes
|
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
|
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)
|
(self, notes: Mapping[str, str]) -> NoneType
|
708,300
|
gspread.worksheet
|
update_tab_color
|
Changes the worksheet's tab color.
Use clear_tab_color() to remove the color.
:param str color: Hex color value.
|
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
|
(self, color: str) -> MutableMapping[str, Any]
|
708,301
|
gspread.worksheet
|
update_title
|
Renames the worksheet.
:param str title: A new title.
|
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
|
(self, title: str) -> MutableMapping[str, Any]
|
708,302
|
gspread.exceptions
|
WorksheetNotFound
|
Trying to open non-existent or inaccessible worksheet.
|
class WorksheetNotFound(GSpreadException):
"""Trying to open non-existent or inaccessible worksheet."""
| null |
708,303
|
gspread.auth
|
api_key
|
Authenticate using an API key.
Allows you to open public spreadsheet files.
.. warning::
This method only allows you to open public spreadsheet files.
It does not work for private spreadsheet files.
:param token str: The actual API key to use
:type http_client: :class:`gspread.http_client.HTTPClient`
:param http_client: A factory function that returns a client class.
Defaults to :class:`gspread.http_client.HTTPClient` (but could also use
:class:`gspread.http_client.BackOffHTTPClient` to avoid rate limiting)
:rtype: :class:`gspread.client.Client`
|
def api_key(token: str, http_client: HTTPClientType = HTTPClient) -> Client:
"""Authenticate using an API key.
Allows you to open public spreadsheet files.
.. warning::
This method only allows you to open public spreadsheet files.
It does not work for private spreadsheet files.
:param token str: The actual API key to use
:type http_client: :class:`gspread.http_client.HTTPClient`
:param http_client: A factory function that returns a client class.
Defaults to :class:`gspread.http_client.HTTPClient` (but could also use
:class:`gspread.http_client.BackOffHTTPClient` to avoid rate limiting)
:rtype: :class:`gspread.client.Client`
"""
creds = APIKeyCredentials(token)
return Client(auth=creds, http_client=http_client)
|
(token: str, http_client: Type[gspread.http_client.HTTPClient] = <class 'gspread.http_client.HTTPClient'>) -> gspread.client.Client
|
708,305
|
gspread.auth
|
authorize
|
Login to Google API using OAuth2 credentials.
This is a shortcut/helper function which
instantiates a client using `http_client`.
By default :class:`gspread.HTTPClient` is used (but could also use
:class:`gspread.BackOffHTTPClient` to avoid rate limiting).
It can take an additional `requests.Session` object in order to provide
you own session object.
.. note::
When providing your own `requests.Session` object,
use the value `None` as `credentials`.
:returns: An instance of the class produced by `http_client`.
:rtype: :class:`gspread.client.Client`
|
def authorize(
credentials: Credentials,
http_client: HTTPClientType = HTTPClient,
session: Optional[Session] = None,
) -> Client:
"""Login to Google API using OAuth2 credentials.
This is a shortcut/helper function which
instantiates a client using `http_client`.
By default :class:`gspread.HTTPClient` is used (but could also use
:class:`gspread.BackOffHTTPClient` to avoid rate limiting).
It can take an additional `requests.Session` object in order to provide
you own session object.
.. note::
When providing your own `requests.Session` object,
use the value `None` as `credentials`.
:returns: An instance of the class produced by `http_client`.
:rtype: :class:`gspread.client.Client`
"""
return Client(auth=credentials, session=session, http_client=http_client)
|
(credentials: google.auth.credentials.Credentials, http_client: Type[gspread.http_client.HTTPClient] = <class 'gspread.http_client.HTTPClient'>, session: Optional[requests.sessions.Session] = None) -> gspread.client.Client
|
708,310
|
gspread.auth
|
oauth
|
Authenticate with OAuth Client ID.
By default this function will use the local server strategy and open
the authorization URL in the user's browser::
gc = gspread.oauth()
Another option is to run a console strategy. This way, the user is
instructed to open the authorization URL in their browser. Once the
authorization is complete, the user must then copy & paste the
authorization code into the application::
gc = gspread.oauth(flow=gspread.auth.console_flow)
``scopes`` parameter defaults to read/write scope available in
``gspread.auth.DEFAULT_SCOPES``. It's read/write for Sheets
and Drive API::
DEFAULT_SCOPES =[
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
]
You can also use ``gspread.auth.READONLY_SCOPES`` for read only access.
Obviously any method of ``gspread`` that updates a spreadsheet
**will not work** in this case::
gc = gspread.oauth(scopes=gspread.auth.READONLY_SCOPES)
sh = gc.open("A spreadsheet")
sh.sheet1.update('A1', '42') # <-- this will not work
If you're storing your user credentials in a place other than the
default, you may provide a path to that file like so::
gc = gspread.oauth(
credentials_filename='/alternative/path/credentials.json',
authorized_user_filename='/alternative/path/authorized_user.json',
)
:param list scopes: The scopes used to obtain authorization.
:param function flow: OAuth flow to use for authentication.
Defaults to :meth:`~gspread.auth.local_server_flow`
:param str credentials_filename: Filepath (including name) pointing to a
credentials `.json` file.
Defaults to DEFAULT_CREDENTIALS_FILENAME:
* `%APPDATA%\gspread\credentials.json` on Windows
* `~/.config/gspread/credentials.json` everywhere else
:param str authorized_user_filename: Filepath (including name) pointing to
an authorized user `.json` file.
Defaults to DEFAULT_AUTHORIZED_USER_FILENAME:
* `%APPDATA%\gspread\authorized_user.json` on Windows
* `~/.config/gspread/authorized_user.json` everywhere else
:type http_client: :class:`gspread.http_client.HTTPClient`
:param http_client: A factory function that returns a client class.
Defaults to :class:`gspread.http_client.HTTPClient` (but could also use
:class:`gspread.http_client.BackOffHTTPClient` to avoid rate limiting)
:rtype: :class:`gspread.client.Client`
|
def oauth(
scopes: Iterable[str] = DEFAULT_SCOPES,
flow: FlowCallable = local_server_flow,
credentials_filename: Union[str, Path] = DEFAULT_CREDENTIALS_FILENAME,
authorized_user_filename: Union[str, Path] = DEFAULT_AUTHORIZED_USER_FILENAME,
http_client: HTTPClientType = HTTPClient,
) -> Client:
r"""Authenticate with OAuth Client ID.
By default this function will use the local server strategy and open
the authorization URL in the user's browser::
gc = gspread.oauth()
Another option is to run a console strategy. This way, the user is
instructed to open the authorization URL in their browser. Once the
authorization is complete, the user must then copy & paste the
authorization code into the application::
gc = gspread.oauth(flow=gspread.auth.console_flow)
``scopes`` parameter defaults to read/write scope available in
``gspread.auth.DEFAULT_SCOPES``. It's read/write for Sheets
and Drive API::
DEFAULT_SCOPES =[
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
]
You can also use ``gspread.auth.READONLY_SCOPES`` for read only access.
Obviously any method of ``gspread`` that updates a spreadsheet
**will not work** in this case::
gc = gspread.oauth(scopes=gspread.auth.READONLY_SCOPES)
sh = gc.open("A spreadsheet")
sh.sheet1.update('A1', '42') # <-- this will not work
If you're storing your user credentials in a place other than the
default, you may provide a path to that file like so::
gc = gspread.oauth(
credentials_filename='/alternative/path/credentials.json',
authorized_user_filename='/alternative/path/authorized_user.json',
)
:param list scopes: The scopes used to obtain authorization.
:param function flow: OAuth flow to use for authentication.
Defaults to :meth:`~gspread.auth.local_server_flow`
:param str credentials_filename: Filepath (including name) pointing to a
credentials `.json` file.
Defaults to DEFAULT_CREDENTIALS_FILENAME:
* `%APPDATA%\gspread\credentials.json` on Windows
* `~/.config/gspread/credentials.json` everywhere else
:param str authorized_user_filename: Filepath (including name) pointing to
an authorized user `.json` file.
Defaults to DEFAULT_AUTHORIZED_USER_FILENAME:
* `%APPDATA%\gspread\authorized_user.json` on Windows
* `~/.config/gspread/authorized_user.json` everywhere else
:type http_client: :class:`gspread.http_client.HTTPClient`
:param http_client: A factory function that returns a client class.
Defaults to :class:`gspread.http_client.HTTPClient` (but could also use
:class:`gspread.http_client.BackOffHTTPClient` to avoid rate limiting)
:rtype: :class:`gspread.client.Client`
"""
authorized_user_filename = Path(authorized_user_filename)
creds = load_credentials(filename=authorized_user_filename)
if not isinstance(creds, Credentials):
with open(credentials_filename) as json_file:
client_config = json.load(json_file)
creds = flow(client_config=client_config, scopes=scopes)
store_credentials(creds, filename=authorized_user_filename)
return Client(auth=creds, http_client=http_client)
|
(scopes: Iterable[str] = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive'], flow: gspread.auth.FlowCallable = <function local_server_flow at 0x7fad287e4040>, credentials_filename: Union[str, pathlib.Path] = PosixPath('/root/.config/gspread/credentials.json'), authorized_user_filename: Union[str, pathlib.Path] = PosixPath('/root/.config/gspread/authorized_user.json'), http_client: Type[gspread.http_client.HTTPClient] = <class 'gspread.http_client.HTTPClient'>) -> gspread.client.Client
|
708,311
|
gspread.auth
|
oauth_from_dict
|
Authenticate with OAuth Client ID.
By default this function will use the local server strategy and open
the authorization URL in the user's browser::
gc = gspread.oauth_from_dict()
Another option is to run a console strategy. This way, the user is
instructed to open the authorization URL in their browser. Once the
authorization is complete, the user must then copy & paste the
authorization code into the application::
gc = gspread.oauth_from_dict(flow=gspread.auth.console_flow)
``scopes`` parameter defaults to read/write scope available in
``gspread.auth.DEFAULT_SCOPES``. It's read/write for Sheets
and Drive API::
DEFAULT_SCOPES =[
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
]
You can also use ``gspread.auth.READONLY_SCOPES`` for read only access.
Obviously any method of ``gspread`` that updates a spreadsheet
**will not work** in this case::
gc = gspread.oauth_from_dict(scopes=gspread.auth.READONLY_SCOPES)
sh = gc.open("A spreadsheet")
sh.sheet1.update('A1', '42') # <-- this will not work
This function requires you to pass the credentials directly as
a python dict. After the first authentication the function returns
the authenticated user info, this can be passed again to authenticate
the user without the need to run the flow again.
..
code block below must be explicitly announced using code-block
.. code-block:: python
gc = gspread.oauth_from_dict(
credentials=my_creds,
authorized_user_info=my_auth_user
)
:param dict credentials: The credentials from google cloud platform
:param dict authorized_user_info: The authenticated user
if already authenticated.
:param list scopes: The scopes used to obtain authorization.
:param function flow: OAuth flow to use for authentication.
Defaults to :meth:`~gspread.auth.local_server_flow`
:type http_client: :class:`gspread.http_client.HTTPClient`
:param http_client: A factory function that returns a client class.
Defaults to :class:`gspread.http_client.HTTPClient` (but could also use
:class:`gspread.http_client.BackOffHTTPClient` to avoid rate limiting)
:rtype: (:class:`gspread.client.Client`, str)
|
def oauth_from_dict(
credentials: Optional[Mapping[str, Any]] = None,
authorized_user_info: Optional[Mapping[str, Any]] = None,
scopes: Iterable[str] = DEFAULT_SCOPES,
flow: FlowCallable = local_server_flow,
http_client: HTTPClientType = HTTPClient,
) -> Tuple[Client, Dict[str, Any]]:
r"""Authenticate with OAuth Client ID.
By default this function will use the local server strategy and open
the authorization URL in the user's browser::
gc = gspread.oauth_from_dict()
Another option is to run a console strategy. This way, the user is
instructed to open the authorization URL in their browser. Once the
authorization is complete, the user must then copy & paste the
authorization code into the application::
gc = gspread.oauth_from_dict(flow=gspread.auth.console_flow)
``scopes`` parameter defaults to read/write scope available in
``gspread.auth.DEFAULT_SCOPES``. It's read/write for Sheets
and Drive API::
DEFAULT_SCOPES =[
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
]
You can also use ``gspread.auth.READONLY_SCOPES`` for read only access.
Obviously any method of ``gspread`` that updates a spreadsheet
**will not work** in this case::
gc = gspread.oauth_from_dict(scopes=gspread.auth.READONLY_SCOPES)
sh = gc.open("A spreadsheet")
sh.sheet1.update('A1', '42') # <-- this will not work
This function requires you to pass the credentials directly as
a python dict. After the first authentication the function returns
the authenticated user info, this can be passed again to authenticate
the user without the need to run the flow again.
..
code block below must be explicitly announced using code-block
.. code-block:: python
gc = gspread.oauth_from_dict(
credentials=my_creds,
authorized_user_info=my_auth_user
)
:param dict credentials: The credentials from google cloud platform
:param dict authorized_user_info: The authenticated user
if already authenticated.
:param list scopes: The scopes used to obtain authorization.
:param function flow: OAuth flow to use for authentication.
Defaults to :meth:`~gspread.auth.local_server_flow`
:type http_client: :class:`gspread.http_client.HTTPClient`
:param http_client: A factory function that returns a client class.
Defaults to :class:`gspread.http_client.HTTPClient` (but could also use
:class:`gspread.http_client.BackOffHTTPClient` to avoid rate limiting)
:rtype: (:class:`gspread.client.Client`, str)
"""
creds: Credentials = None
if authorized_user_info is not None:
creds = OAuthCredentials.from_authorized_user_info(authorized_user_info, scopes)
if not creds and credentials is not None:
creds = flow(client_config=credentials, scopes=scopes)
client = Client(auth=creds, http_client=http_client)
# must return the creds to the user
# must strip the token an use the dedicated method from Credentials
# to return a dict "safe to store".
return (client, creds.to_json("token"))
|
(credentials: Optional[Mapping[str, Any]] = None, authorized_user_info: Optional[Mapping[str, Any]] = None, scopes: Iterable[str] = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive'], flow: gspread.auth.FlowCallable = <function local_server_flow at 0x7fad287e4040>, http_client: Type[gspread.http_client.HTTPClient] = <class 'gspread.http_client.HTTPClient'>) -> Tuple[gspread.client.Client, Dict[str, Any]]
|
708,312
|
gspread.auth
|
service_account
|
Authenticate using a service account.
``scopes`` parameter defaults to read/write scope available in
``gspread.auth.DEFAULT_SCOPES``. It's read/write for Sheets
and Drive API::
DEFAULT_SCOPES =[
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
]
You can also use ``gspread.auth.READONLY_SCOPES`` for read only access.
Obviously any method of ``gspread`` that updates a spreadsheet
**will not work** in this case.
:param str filename: The path to the service account json file.
:param list scopes: The scopes used to obtain authorization.
:type http_client: :class:`gspread.http_client.HTTPClient`
:param http_client: A factory function that returns a client class.
Defaults to :class:`gspread.HTTPClient` (but could also use
:class:`gspread.BackOffHTTPClient` to avoid rate limiting)
:rtype: :class:`gspread.client.Client`
|
def service_account(
filename: Union[Path, str] = DEFAULT_SERVICE_ACCOUNT_FILENAME,
scopes: Iterable[str] = DEFAULT_SCOPES,
http_client: HTTPClientType = HTTPClient,
) -> Client:
"""Authenticate using a service account.
``scopes`` parameter defaults to read/write scope available in
``gspread.auth.DEFAULT_SCOPES``. It's read/write for Sheets
and Drive API::
DEFAULT_SCOPES =[
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
]
You can also use ``gspread.auth.READONLY_SCOPES`` for read only access.
Obviously any method of ``gspread`` that updates a spreadsheet
**will not work** in this case.
:param str filename: The path to the service account json file.
:param list scopes: The scopes used to obtain authorization.
:type http_client: :class:`gspread.http_client.HTTPClient`
:param http_client: A factory function that returns a client class.
Defaults to :class:`gspread.HTTPClient` (but could also use
:class:`gspread.BackOffHTTPClient` to avoid rate limiting)
:rtype: :class:`gspread.client.Client`
"""
creds = SACredentials.from_service_account_file(filename, scopes=scopes)
return Client(auth=creds, http_client=http_client)
|
(filename: Union[pathlib.Path, str] = PosixPath('/root/.config/gspread/service_account.json'), scopes: Iterable[str] = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive'], http_client: Type[gspread.http_client.HTTPClient] = <class 'gspread.http_client.HTTPClient'>) -> gspread.client.Client
|
708,313
|
gspread.auth
|
service_account_from_dict
|
Authenticate using a service account (json).
``scopes`` parameter defaults to read/write scope available in
``gspread.auth.DEFAULT_SCOPES``. It's read/write for Sheets
and Drive API::
DEFAULT_SCOPES =[
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
]
You can also use ``gspread.auth.READONLY_SCOPES`` for read only access.
Obviously any method of ``gspread`` that updates a spreadsheet
**will not work** in this case.
:param info (Mapping[str, str]): The service account info in Google format
:param list scopes: The scopes used to obtain authorization.
:type http_client: :class:`gspread.http_client.HTTPClient`
:param http_client: A factory function that returns a client class.
Defaults to :class:`gspread.http_client.HTTPClient` (but could also use
:class:`gspread.http_client.BackOffHTTPClient` to avoid rate limiting)
:rtype: :class:`gspread.client.Client`
|
def service_account_from_dict(
info: Mapping[str, Any],
scopes: Iterable[str] = DEFAULT_SCOPES,
http_client: HTTPClientType = HTTPClient,
) -> Client:
"""Authenticate using a service account (json).
``scopes`` parameter defaults to read/write scope available in
``gspread.auth.DEFAULT_SCOPES``. It's read/write for Sheets
and Drive API::
DEFAULT_SCOPES =[
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
]
You can also use ``gspread.auth.READONLY_SCOPES`` for read only access.
Obviously any method of ``gspread`` that updates a spreadsheet
**will not work** in this case.
:param info (Mapping[str, str]): The service account info in Google format
:param list scopes: The scopes used to obtain authorization.
:type http_client: :class:`gspread.http_client.HTTPClient`
:param http_client: A factory function that returns a client class.
Defaults to :class:`gspread.http_client.HTTPClient` (but could also use
:class:`gspread.http_client.BackOffHTTPClient` to avoid rate limiting)
:rtype: :class:`gspread.client.Client`
"""
creds = SACredentials.from_service_account_info(
info=info,
scopes=scopes,
)
return Client(auth=creds, http_client=http_client)
|
(info: Mapping[str, Any], scopes: Iterable[str] = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive'], http_client: Type[gspread.http_client.HTTPClient] = <class 'gspread.http_client.HTTPClient'>) -> gspread.client.Client
|
708,318
|
qpd.qpd_engine
|
QPDEngine
| null |
class QPDEngine(ABC):
def __call__(self, func_name: str, *args: Any, **kwargs: Any) -> Any:
return getattr(self, func_name)(*args, **kwargs)
def rename(self, col: Column, name: str) -> Column:
return col.rename(name)
def extract_col(self, df: DataFrame, name: str) -> Column:
return df[name]
def assemble_df(self, *args: Any) -> DataFrame:
return DataFrame(*args)
@property
@abstractmethod
def pl_utils(self) -> PandasLikeUtils:
raise NotImplementedError
@abstractmethod
def to_df(self, obj: Any) -> DataFrame: # pragma: no cover
raise NotImplementedError
@abstractmethod
def to_col(self, value: Any, name: str = "") -> Column: # pragma: no cover
raise NotImplementedError
@abstractmethod
def to_native(self, df: DataFrame) -> Any: # pragma: no cover
raise NotImplementedError
@abstractmethod
def is_series(self, obj: Any) -> bool: # pragma: no cover
raise NotImplementedError
@abstractmethod
def case_when(self, *cols: Column) -> Column: # pragma: no cover
"""`cols` must be in the format of
`when1`, `value1`, ... ,`default`, and length must be >= 3.
The reason to design the interface in this way is to simplify the translation
from SQL to engine APIs.
:return: [description]
:rtype: Column
"""
raise NotImplementedError
@abstractmethod
def order_by_limit(
self, df: DataFrame, order_by: OrderBySpec, limit: int
) -> DataFrame: # pragma: no cover
raise NotImplementedError
@abstractmethod
def group_agg(
self,
df: DataFrame,
keys: List[str],
agg_map: Dict[str, Tuple[str, AggFunctionSpec]],
) -> DataFrame: # pragma: no cover
raise NotImplementedError
@abstractmethod
def window( # noqa: C901
self,
df: DataFrame,
func: WindowFunctionSpec,
args: List[ArgumentSpec],
dest_col_name: str,
) -> DataFrame: # pragma: no cover
raise NotImplementedError
def basic_unary_arithmetic_op(self, col: Column, op: str) -> Column:
if op == "+":
return col
if op == "-":
return Column(0 - col.native)
raise NotImplementedError(f"{op} is not supported") # pragma: no cover
def binary_arithmetic_op(self, col1: Column, col2: Column, op: str) -> Column:
if op == "+":
return Column(col1.native + col2.native)
if op == "-":
return Column(col1.native - col2.native)
if op == "*":
return Column(col1.native * col2.native)
if op == "/":
return Column(col1.native / col2.native)
raise NotImplementedError(f"{op} is not supported") # pragma: no cover
def comparison_op(self, col1: Column, col2: Column, op: str) -> Column:
if op == "==":
s: Any = col1.native == col2.native
elif op == "!=":
s = col1.native != col2.native
elif op == "<":
s = col1.native < col2.native
elif op == "<=":
s = col1.native <= col2.native
elif op == ">":
s = col1.native > col2.native
elif op == ">=":
s = col1.native >= col2.native
else: # pragma: no cover
raise NotImplementedError(f"{op} is not supported")
return self._set_op_result_to_none(s, col1.native, col2.native)
def binary_logical_op(self, col1: Column, col2: Column, op: str) -> Column:
c1 = self._safe_bool(col1)
c2 = self._safe_bool(col2)
if op == "and":
s: Any = c1 * c2
# in sql, FALSE AND anything is False
if self.is_series(s):
s = s.mask((c1 == 0) | (c2 == 0), 0)
elif (c1 == 0) | (c2 == 0):
s = 0.0
elif op == "or":
s = c1 + c2
# in sql, True OR anything is True
if self.is_series(s):
s = s.mask((c1 > 0) | (c2 > 0), 1)
elif (c1 > 0) | (c2 > 0):
s = 1.0
else: # pragma: no cover
raise NotImplementedError(f"{op} is not supported")
return Column(s)
def logical_not(self, col: Column) -> Column:
s = self._safe_bool(col.native)
if self.is_series(s):
nulls = s.isnull()
s = s == 0
s = s.mask(nulls, None)
return Column(s)
return Column(1.0 - s)
def filter_df(self, df: DataFrame, cond: Column) -> DataFrame:
c = self._safe_bool(cond)
if self.is_series(c):
ndf = self.to_native(df)[c > 0]
return self.to_df(ndf)
elif c > 0:
return df
else:
ndf = self.to_native(df).head(0)
return self.to_df(ndf)
def is_value(self, col: Column, is_value: IsValueSpec) -> Column:
v = is_value.value_expr
if v == "null":
if is_value.positive:
return Column(col.native.isnull())
else:
return Column(~col.native.isnull())
if v == "true":
if is_value.positive:
return Column(col.native == True) # noqa:
else:
return Column(col.native != True) # noqa:
if v == "false":
if is_value.positive:
return Column(col.native == False) # noqa:
else:
return Column(col.native != False) # noqa:
raise NotImplementedError(v) # pragma: no cover
def is_in(self, col: Column, *values: Any, positive: bool) -> Column:
cols = [x for x in values if isinstance(x, Column)]
others = [x for x in values if not isinstance(x, Column)]
if positive:
o: Any = col.native.isin(others)
for c in cols:
o = o | col.native == c.native
else:
o = ~col.native.isin(others)
for c in cols:
o = o & col.native != c.native
if self.is_series(o) and self.is_series(col.native):
o = o.mask(col.native.isnull(), None)
return Column(o)
def is_between(
self, col: Column, lower: Column, upper: Column, positive: bool
) -> Column:
ln = lower.native
cn = col.native
un = upper.native
if positive:
s: Any = (ln <= cn) & (cn <= un)
else:
s = (ln > cn) | (cn > un)
if self.is_series(col.native):
s = s.mask(col.native.isnull(), None)
if self.is_series(lower.native):
s = s.mask(lower.native.isnull(), None)
if self.is_series(upper.native):
s = s.mask(upper.native.isnull(), None)
return Column(s)
def drop_duplicates(self, df: DataFrame) -> DataFrame:
ndf = self.to_native(df)
return self.to_df(self.pl_utils.drop_duplicates(ndf))
def union(self, df1: DataFrame, df2: DataFrame, unique: bool) -> DataFrame:
ndf1 = self.to_native(df1)
ndf2 = self.to_native(df2)
return self.to_df(self.pl_utils.union(ndf1, ndf2, unique))
def intersect(self, df1: DataFrame, df2: DataFrame, unique: bool) -> DataFrame:
ndf1 = self.to_native(df1)
ndf2 = self.to_native(df2)
return self.to_df(self.pl_utils.intersect(ndf1, ndf2, unique))
def except_df(self, df1: DataFrame, df2: DataFrame, unique: bool) -> DataFrame:
ndf1 = self.to_native(df1)
ndf2 = self.to_native(df2)
return self.to_df(self.pl_utils.except_df(ndf1, ndf2, unique))
def join(
self, df1: DataFrame, df2: DataFrame, join_type: str, on: List[str]
) -> DataFrame:
ndf1 = self.to_native(df1)
ndf2 = self.to_native(df2)
joined = self.pl_utils.join(ndf1, ndf2, join_type=join_type, on=on)
return self.to_df(joined)
def _set_op_result_to_none(self, series: Any, s1: Any, s2: Any) -> Column:
if not self.is_series(series):
if s1 is None or s2 is None:
return Column(None)
return Column(series)
if self.is_series(s1):
series = series.mask(s1.isnull(), None)
if self.is_series(s2):
series = series.mask(s2.isnull(), None)
return Column(series)
def _preprocess_set_op(self, df1: DataFrame, df2: DataFrame) -> Tuple[Any, Any]:
assert_or_throw(
len(df1) == len(df2),
ValueError("two dataframes have different number of columns"),
)
ndf1 = self.to_native(df1)
ndf2 = self.to_native(df2)
ndf2.columns = ndf1.columns # this is SQL behavior
return ndf1, ndf2
def _safe_bool(self, col: Any) -> Any:
if self.is_series(col):
return col.astype("f8")
if self.is_series(col.native):
return col.native.astype("f8")
elif col is None:
return float("nan")
else:
return float(col.native > 0)
|
()
|
708,319
|
qpd.qpd_engine
|
__call__
| null |
def __call__(self, func_name: str, *args: Any, **kwargs: Any) -> Any:
return getattr(self, func_name)(*args, **kwargs)
|
(self, func_name: str, *args: Any, **kwargs: Any) -> Any
|
708,320
|
qpd.qpd_engine
|
_preprocess_set_op
| null |
def _preprocess_set_op(self, df1: DataFrame, df2: DataFrame) -> Tuple[Any, Any]:
assert_or_throw(
len(df1) == len(df2),
ValueError("two dataframes have different number of columns"),
)
ndf1 = self.to_native(df1)
ndf2 = self.to_native(df2)
ndf2.columns = ndf1.columns # this is SQL behavior
return ndf1, ndf2
|
(self, df1: qpd.dataframe.DataFrame, df2: qpd.dataframe.DataFrame) -> Tuple[Any, Any]
|
708,321
|
qpd.qpd_engine
|
_safe_bool
| null |
def _safe_bool(self, col: Any) -> Any:
if self.is_series(col):
return col.astype("f8")
if self.is_series(col.native):
return col.native.astype("f8")
elif col is None:
return float("nan")
else:
return float(col.native > 0)
|
(self, col: Any) -> Any
|
708,322
|
qpd.qpd_engine
|
_set_op_result_to_none
| null |
def _set_op_result_to_none(self, series: Any, s1: Any, s2: Any) -> Column:
if not self.is_series(series):
if s1 is None or s2 is None:
return Column(None)
return Column(series)
if self.is_series(s1):
series = series.mask(s1.isnull(), None)
if self.is_series(s2):
series = series.mask(s2.isnull(), None)
return Column(series)
|
(self, series: Any, s1: Any, s2: Any) -> qpd.dataframe.Column
|
708,323
|
qpd.qpd_engine
|
assemble_df
| null |
def assemble_df(self, *args: Any) -> DataFrame:
return DataFrame(*args)
|
(self, *args: Any) -> qpd.dataframe.DataFrame
|
708,324
|
qpd.qpd_engine
|
basic_unary_arithmetic_op
| null |
def basic_unary_arithmetic_op(self, col: Column, op: str) -> Column:
if op == "+":
return col
if op == "-":
return Column(0 - col.native)
raise NotImplementedError(f"{op} is not supported") # pragma: no cover
|
(self, col: qpd.dataframe.Column, op: str) -> qpd.dataframe.Column
|
708,325
|
qpd.qpd_engine
|
binary_arithmetic_op
| null |
def binary_arithmetic_op(self, col1: Column, col2: Column, op: str) -> Column:
if op == "+":
return Column(col1.native + col2.native)
if op == "-":
return Column(col1.native - col2.native)
if op == "*":
return Column(col1.native * col2.native)
if op == "/":
return Column(col1.native / col2.native)
raise NotImplementedError(f"{op} is not supported") # pragma: no cover
|
(self, col1: qpd.dataframe.Column, col2: qpd.dataframe.Column, op: str) -> qpd.dataframe.Column
|
708,326
|
qpd.qpd_engine
|
binary_logical_op
| null |
def binary_logical_op(self, col1: Column, col2: Column, op: str) -> Column:
c1 = self._safe_bool(col1)
c2 = self._safe_bool(col2)
if op == "and":
s: Any = c1 * c2
# in sql, FALSE AND anything is False
if self.is_series(s):
s = s.mask((c1 == 0) | (c2 == 0), 0)
elif (c1 == 0) | (c2 == 0):
s = 0.0
elif op == "or":
s = c1 + c2
# in sql, True OR anything is True
if self.is_series(s):
s = s.mask((c1 > 0) | (c2 > 0), 1)
elif (c1 > 0) | (c2 > 0):
s = 1.0
else: # pragma: no cover
raise NotImplementedError(f"{op} is not supported")
return Column(s)
|
(self, col1: qpd.dataframe.Column, col2: qpd.dataframe.Column, op: str) -> qpd.dataframe.Column
|
708,327
|
qpd.qpd_engine
|
case_when
|
`cols` must be in the format of
`when1`, `value1`, ... ,`default`, and length must be >= 3.
The reason to design the interface in this way is to simplify the translation
from SQL to engine APIs.
:return: [description]
:rtype: Column
|
@abstractmethod
def case_when(self, *cols: Column) -> Column: # pragma: no cover
"""`cols` must be in the format of
`when1`, `value1`, ... ,`default`, and length must be >= 3.
The reason to design the interface in this way is to simplify the translation
from SQL to engine APIs.
:return: [description]
:rtype: Column
"""
raise NotImplementedError
|
(self, *cols: qpd.dataframe.Column) -> qpd.dataframe.Column
|
708,328
|
qpd.qpd_engine
|
comparison_op
| null |
def comparison_op(self, col1: Column, col2: Column, op: str) -> Column:
if op == "==":
s: Any = col1.native == col2.native
elif op == "!=":
s = col1.native != col2.native
elif op == "<":
s = col1.native < col2.native
elif op == "<=":
s = col1.native <= col2.native
elif op == ">":
s = col1.native > col2.native
elif op == ">=":
s = col1.native >= col2.native
else: # pragma: no cover
raise NotImplementedError(f"{op} is not supported")
return self._set_op_result_to_none(s, col1.native, col2.native)
|
(self, col1: qpd.dataframe.Column, col2: qpd.dataframe.Column, op: str) -> qpd.dataframe.Column
|
708,329
|
qpd.qpd_engine
|
drop_duplicates
| null |
def drop_duplicates(self, df: DataFrame) -> DataFrame:
ndf = self.to_native(df)
return self.to_df(self.pl_utils.drop_duplicates(ndf))
|
(self, df: qpd.dataframe.DataFrame) -> qpd.dataframe.DataFrame
|
708,330
|
qpd.qpd_engine
|
except_df
| null |
def except_df(self, df1: DataFrame, df2: DataFrame, unique: bool) -> DataFrame:
ndf1 = self.to_native(df1)
ndf2 = self.to_native(df2)
return self.to_df(self.pl_utils.except_df(ndf1, ndf2, unique))
|
(self, df1: qpd.dataframe.DataFrame, df2: qpd.dataframe.DataFrame, unique: bool) -> qpd.dataframe.DataFrame
|
708,331
|
qpd.qpd_engine
|
extract_col
| null |
def extract_col(self, df: DataFrame, name: str) -> Column:
return df[name]
|
(self, df: qpd.dataframe.DataFrame, name: str) -> qpd.dataframe.Column
|
708,332
|
qpd.qpd_engine
|
filter_df
| null |
def filter_df(self, df: DataFrame, cond: Column) -> DataFrame:
c = self._safe_bool(cond)
if self.is_series(c):
ndf = self.to_native(df)[c > 0]
return self.to_df(ndf)
elif c > 0:
return df
else:
ndf = self.to_native(df).head(0)
return self.to_df(ndf)
|
(self, df: qpd.dataframe.DataFrame, cond: qpd.dataframe.Column) -> qpd.dataframe.DataFrame
|
708,333
|
qpd.qpd_engine
|
group_agg
| null |
@abstractmethod
def group_agg(
self,
df: DataFrame,
keys: List[str],
agg_map: Dict[str, Tuple[str, AggFunctionSpec]],
) -> DataFrame: # pragma: no cover
raise NotImplementedError
|
(self, df: qpd.dataframe.DataFrame, keys: List[str], agg_map: Dict[str, Tuple[str, qpd.specs.AggFunctionSpec]]) -> qpd.dataframe.DataFrame
|
708,334
|
qpd.qpd_engine
|
intersect
| null |
def intersect(self, df1: DataFrame, df2: DataFrame, unique: bool) -> DataFrame:
ndf1 = self.to_native(df1)
ndf2 = self.to_native(df2)
return self.to_df(self.pl_utils.intersect(ndf1, ndf2, unique))
|
(self, df1: qpd.dataframe.DataFrame, df2: qpd.dataframe.DataFrame, unique: bool) -> qpd.dataframe.DataFrame
|
708,335
|
qpd.qpd_engine
|
is_between
| null |
def is_between(
self, col: Column, lower: Column, upper: Column, positive: bool
) -> Column:
ln = lower.native
cn = col.native
un = upper.native
if positive:
s: Any = (ln <= cn) & (cn <= un)
else:
s = (ln > cn) | (cn > un)
if self.is_series(col.native):
s = s.mask(col.native.isnull(), None)
if self.is_series(lower.native):
s = s.mask(lower.native.isnull(), None)
if self.is_series(upper.native):
s = s.mask(upper.native.isnull(), None)
return Column(s)
|
(self, col: qpd.dataframe.Column, lower: qpd.dataframe.Column, upper: qpd.dataframe.Column, positive: bool) -> qpd.dataframe.Column
|
708,336
|
qpd.qpd_engine
|
is_in
| null |
def is_in(self, col: Column, *values: Any, positive: bool) -> Column:
cols = [x for x in values if isinstance(x, Column)]
others = [x for x in values if not isinstance(x, Column)]
if positive:
o: Any = col.native.isin(others)
for c in cols:
o = o | col.native == c.native
else:
o = ~col.native.isin(others)
for c in cols:
o = o & col.native != c.native
if self.is_series(o) and self.is_series(col.native):
o = o.mask(col.native.isnull(), None)
return Column(o)
|
(self, col: qpd.dataframe.Column, *values: Any, positive: bool) -> qpd.dataframe.Column
|
708,337
|
qpd.qpd_engine
|
is_series
| null |
@abstractmethod
def is_series(self, obj: Any) -> bool: # pragma: no cover
raise NotImplementedError
|
(self, obj: Any) -> bool
|
708,338
|
qpd.qpd_engine
|
is_value
| null |
def is_value(self, col: Column, is_value: IsValueSpec) -> Column:
v = is_value.value_expr
if v == "null":
if is_value.positive:
return Column(col.native.isnull())
else:
return Column(~col.native.isnull())
if v == "true":
if is_value.positive:
return Column(col.native == True) # noqa:
else:
return Column(col.native != True) # noqa:
if v == "false":
if is_value.positive:
return Column(col.native == False) # noqa:
else:
return Column(col.native != False) # noqa:
raise NotImplementedError(v) # pragma: no cover
|
(self, col: qpd.dataframe.Column, is_value: qpd.specs.IsValueSpec) -> qpd.dataframe.Column
|
708,339
|
qpd.qpd_engine
|
join
| null |
def join(
self, df1: DataFrame, df2: DataFrame, join_type: str, on: List[str]
) -> DataFrame:
ndf1 = self.to_native(df1)
ndf2 = self.to_native(df2)
joined = self.pl_utils.join(ndf1, ndf2, join_type=join_type, on=on)
return self.to_df(joined)
|
(self, df1: qpd.dataframe.DataFrame, df2: qpd.dataframe.DataFrame, join_type: str, on: List[str]) -> qpd.dataframe.DataFrame
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.