python-google-sheets 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,22 @@
1
+ from .styles import Color_, Border_
2
+ from .spreadsheet_requests import (
3
+ ColorStyle,
4
+ CellFormat,
5
+ Dimension,
6
+ NumberFormat,
7
+ NumberFormatType,
8
+ TextFormat,
9
+ TextDirection,
10
+ TextRotation,
11
+ Borders,
12
+ Border,
13
+ BorderStyle,
14
+ HorizontalAlignment,
15
+ VerticalAlignment,
16
+ WrapStrategy,
17
+ Spreadsheet,
18
+ SheetProperties,
19
+ )
20
+ from .utils import col_num_to_letter, float_sum, rowcol_to_a1
21
+ from .api_request import ApiRequest
22
+ from .google_sheets import GoogleSheets
@@ -0,0 +1,453 @@
1
+ import re
2
+
3
+ from .spreadsheet_requests import (
4
+ # conditional_format_rule
5
+ AddConditionalFormatRule,
6
+ DeleteConditionalFormatRule,
7
+ UpdateConditionalFormatRule,
8
+ ConditionalFormatRule,
9
+ GradientRule,
10
+ InterpolationPoint,
11
+ InterpolationPointType,
12
+
13
+ # update_sheet_properties
14
+ UpdateSheetProperties,
15
+ SheetProperties,
16
+ GridProperties,
17
+
18
+ # merge_cells
19
+ MergeType,
20
+ MergeCells,
21
+ UnmergeCells,
22
+
23
+ # dimension
24
+ InsertDimension,
25
+ UpdateDimensionProperties,
26
+ AddDimensionGroup,
27
+ DeleteDimensionGroup,
28
+ DimensionProperties,
29
+ DimensionRange,
30
+ Dimension,
31
+
32
+ # update_cells
33
+ UpdateCells,
34
+ RowData,
35
+ CellData,
36
+ ExtendedValue,
37
+ CellFormat,
38
+
39
+ # general_models
40
+ ColorStyle,
41
+ GridRange,
42
+ FieldMask,
43
+
44
+ # spreadsheet
45
+ AddSheet,
46
+ DeleteSheet,
47
+ )
48
+
49
+
50
+ class ApiRequest:
51
+ @staticmethod
52
+ def update_cells(
53
+ sheet_id: int,
54
+ range_: str,
55
+ values: list[list[int | float | bool | str]] | list[int | float | bool | str] = None,
56
+ cell_formats: list[list[CellFormat]] | list[CellFormat] = None
57
+ ) -> dict:
58
+ assert values or cell_formats, 'At least one of the parameters must be specified: values or cell_formats'
59
+ start_row, end_row, start_col, end_col = ApiRequest.__split_excel_range(range_)
60
+
61
+ # syntax sugar for single row or column
62
+ if values and not isinstance(values[0], list):
63
+ if start_row == end_row:
64
+ values = [values]
65
+ elif start_col == end_col:
66
+ values = [[value] for value in values]
67
+ if cell_formats and not isinstance(cell_formats[0], list):
68
+ if start_row == end_row:
69
+ cell_formats = [cell_formats]
70
+ elif start_col == end_col:
71
+ cell_formats = [[cell_format] for cell_format in cell_formats]
72
+
73
+ if values is None:
74
+ values = [[None] * len(cell_formats[0]) for _ in cell_formats]
75
+ fields = FieldMask.CellData.USER_ENTERED_FORMAT
76
+ elif cell_formats is None:
77
+ cell_formats = [[None] * len(values[0]) for _ in values]
78
+ fields = FieldMask.CellData.USER_ENTERED_VALUE
79
+ else: # Both values and cell_formats are specified
80
+ fields = '*'
81
+
82
+ return UpdateCells(
83
+ range=GridRange(
84
+ sheet_id=sheet_id,
85
+ start_row_index=start_row - 1,
86
+ end_row_index=end_row,
87
+ start_column_index=start_col - 1,
88
+ end_column_index=end_col
89
+ ),
90
+ rows=[RowData(
91
+ values=[CellData(
92
+ user_entered_value=ExtendedValue(
93
+ number_value=value if isinstance(value, (int, float)) and not isinstance(value, bool) else None,
94
+ bool_value=value if isinstance(value, bool) else None,
95
+ string_value=value if isinstance(value, str) and not value.startswith('=') else None,
96
+ formula_value=value if isinstance(value, str) and value.startswith('=') else None
97
+ ) if value is not None else None,
98
+ user_entered_format=cell_format
99
+ ) for value, cell_format in zip(values_row, cell_formats_row)]
100
+ ) for values_row, cell_formats_row in zip(values, cell_formats)],
101
+ fields=fields
102
+ ).dict()
103
+
104
+ @staticmethod
105
+ def add_conditional_format_rule(
106
+ *,
107
+ sheet_id: int,
108
+ ranges: list[str],
109
+ gradient_colors: tuple[ColorStyle, ColorStyle, ColorStyle] | tuple[ColorStyle, ColorStyle],
110
+ gradient_points: tuple[float, float, float] = None
111
+ ) -> dict:
112
+ grid_ranges = [GridRange(sheet_id=sheet_id, **ApiRequest.__split_excel_range(range_, return_as_dict=True)) for range_ in ranges]
113
+ if gradient_points is None:
114
+ gradient_points = (None,) * len(gradient_colors)
115
+ if len(gradient_colors) == 2:
116
+ return AddConditionalFormatRule(rule=ConditionalFormatRule(
117
+ ranges=grid_ranges,
118
+ gradient_rule=GradientRule(
119
+ minpoint=InterpolationPoint(
120
+ color_style=gradient_colors[0],
121
+ type=InterpolationPointType.MIN,
122
+ value=str(gradient_points[0])
123
+ ),
124
+ maxpoint=InterpolationPoint(
125
+ color_style=gradient_colors[1],
126
+ type=InterpolationPointType.MAX,
127
+ value=str(gradient_points[1])
128
+ )
129
+ )
130
+ )).dict()
131
+ return AddConditionalFormatRule(rule=ConditionalFormatRule(
132
+ ranges=grid_ranges,
133
+ gradient_rule=GradientRule(
134
+ minpoint=InterpolationPoint(
135
+ color_style=gradient_colors[0],
136
+ type=InterpolationPointType.NUMBER,
137
+ value=str(gradient_points[0])
138
+ ),
139
+ midpoint=InterpolationPoint(
140
+ color_style=gradient_colors[1],
141
+ type=InterpolationPointType.NUMBER,
142
+ value=str(gradient_points[1])
143
+ ),
144
+ maxpoint=InterpolationPoint(
145
+ color_style=gradient_colors[2],
146
+ type=InterpolationPointType.NUMBER,
147
+ value=str(gradient_points[2])
148
+ )
149
+ )
150
+ )).dict()
151
+
152
+ @staticmethod
153
+ def delete_conditional_format_rule(*, sheet_id: int, index: int) -> dict:
154
+ return DeleteConditionalFormatRule(sheet_id=sheet_id, index=index).dict()
155
+
156
+ @staticmethod
157
+ def update_conditional_format_rule(*, sheet_id: int, index: int, rule: ConditionalFormatRule) -> dict:
158
+ return UpdateConditionalFormatRule(sheet_id=sheet_id, index=index, rule=rule).dict()
159
+
160
+ @staticmethod
161
+ def update_sheet_title(sheet_id: int, title: str) -> dict:
162
+ return UpdateSheetProperties(
163
+ properties=SheetProperties(
164
+ sheet_id=sheet_id,
165
+ title=title
166
+ ),
167
+ fields=FieldMask.TITLE
168
+ ).dict()
169
+
170
+ @staticmethod
171
+ def remove_grid(sheet_id: int) -> dict:
172
+ return UpdateSheetProperties(
173
+ properties=SheetProperties(
174
+ sheet_id=sheet_id,
175
+ grid_properties=GridProperties(hide_grid_lines=True)
176
+ ),
177
+ fields=FieldMask.GridProperties.HIDE_GRID_LINES
178
+ ).dict()
179
+
180
+ @staticmethod
181
+ def set_sheet_size(sheet_id: int, rows: int = None, columns: int = None) -> dict:
182
+ assert rows is not None or columns is not None, 'At least one of the parameters must be specified: rows or columns'
183
+ if rows and columns:
184
+ fields = f'{FieldMask.GridProperties.ROW_COUNT},{FieldMask.GridProperties.COLUMN_COUNT}'
185
+ elif rows:
186
+ fields = FieldMask.GridProperties.ROW_COUNT
187
+ else:
188
+ fields = FieldMask.GridProperties.COLUMN_COUNT
189
+
190
+ return UpdateSheetProperties(
191
+ properties=SheetProperties(
192
+ sheet_id=sheet_id,
193
+ grid_properties=GridProperties(
194
+ row_count=rows,
195
+ column_count=columns
196
+ )
197
+ ),
198
+ fields=fields
199
+ ).dict()
200
+
201
+ @staticmethod
202
+ def merge_cells(sheet_id: int, range_: str, merge_type: MergeType = MergeType.MERGE_ALL) -> dict:
203
+ start_row, end_row, start_col, end_col = ApiRequest.__split_excel_range(range_)
204
+ return MergeCells(
205
+ range=GridRange(
206
+ sheet_id=sheet_id,
207
+ start_row_index=start_row - 1,
208
+ end_row_index=end_row,
209
+ start_column_index=start_col - 1,
210
+ end_column_index=end_col
211
+ ),
212
+ merge_type=merge_type
213
+ ).dict()
214
+
215
+ @staticmethod
216
+ def unmerge_cells(
217
+ sheet_id: int,
218
+ range_: str = None,
219
+ start_row: int = None,
220
+ end_row: int = None,
221
+ start_column: int | str = None,
222
+ end_column: int | str = None,
223
+ ) -> dict:
224
+ assert range_ or (start_row and end_row and start_column and end_column), 'Either range_ or start_row, end_row, start_column, end_column must be specified'
225
+ if range_: # range_ has priority
226
+ start_row, end_row, start_column, end_column = ApiRequest.__split_excel_range(range_)
227
+ else:
228
+ start_column = ApiRequest.__get_column_index(start_column) if isinstance(start_column, str) else start_column
229
+ end_column = ApiRequest.__get_column_index(end_column) if isinstance(end_column, str) else end_column
230
+ return UnmergeCells(
231
+ range=GridRange(
232
+ sheet_id=sheet_id,
233
+ start_row_index=start_row - 1,
234
+ end_row_index=end_row,
235
+ start_column_index=start_column - 1,
236
+ end_column_index=end_column
237
+ )
238
+ ).dict()
239
+
240
+ @staticmethod
241
+ def freeze(sheet_id: int, rows: int = 0, columns: int = 0) -> dict:
242
+ return UpdateSheetProperties(
243
+ properties=SheetProperties(
244
+ sheet_id=sheet_id,
245
+ grid_properties=GridProperties(
246
+ frozen_row_count=rows,
247
+ frozen_column_count=columns
248
+ )
249
+ ),
250
+ fields=f'{FieldMask.GridProperties.FROZEN_ROW_COUNT},{FieldMask.GridProperties.FROZEN_COLUMN_COUNT}'
251
+ ).dict()
252
+
253
+ @staticmethod
254
+ def insert_rows(sheet_id: int, start_index: int, end_index: int = None, inherit_from_before: bool = True) -> dict:
255
+ """
256
+ Indexes are zero-based and inclusive [start_index, end_index]. If end_index is not specified, then a single
257
+ row will be inserted at start_index.
258
+ """
259
+ end_index = end_index or start_index
260
+ return InsertDimension(
261
+ range=DimensionRange(
262
+ sheet_id=sheet_id,
263
+ dimension=Dimension.ROWS,
264
+ start_index=start_index,
265
+ end_index=end_index + 1
266
+ ),
267
+ inherit_from_before=inherit_from_before
268
+ ).dict()
269
+
270
+ @staticmethod
271
+ def insert_columns(sheet_id: int, start_index: int, end_index: int = None, inherit_from_before: bool = True) -> dict:
272
+ """
273
+ Indexes are zero-based and inclusive [start_index, end_index]. If end_index is not specified, then a single
274
+ column will be inserted at start_index.
275
+ """
276
+ end_index = end_index or start_index
277
+ return InsertDimension(
278
+ range=DimensionRange(
279
+ sheet_id=sheet_id,
280
+ dimension=Dimension.COLUMNS,
281
+ start_index=start_index,
282
+ end_index=end_index + 1
283
+ ),
284
+ inherit_from_before=inherit_from_before
285
+ ).dict()
286
+
287
+ @staticmethod
288
+ def clear_columns(sheet_id: int, rows_count: int, start_index: int, end_index: int = None) -> dict:
289
+ """
290
+ Delete data and formatting in columns. Indexes are zero-based and inclusive [start_index, end_index].
291
+ """
292
+ end_index = end_index or start_index
293
+ return UpdateCells(
294
+ range=GridRange(
295
+ sheet_id=sheet_id,
296
+ start_row_index=0,
297
+ end_row_index=rows_count,
298
+ start_column_index=start_index,
299
+ end_column_index=end_index + 1
300
+ ),
301
+ fields='*'
302
+ ).dict()
303
+
304
+ @staticmethod
305
+ def set_column_width(sheet_id: int, col_no_or_letter: int | str, width: int) -> dict:
306
+ if isinstance(col_no_or_letter, str):
307
+ col_no = ApiRequest.__get_column_index(col_no_or_letter)
308
+ else:
309
+ col_no = col_no_or_letter
310
+ return UpdateDimensionProperties(
311
+ range=DimensionRange(
312
+ sheet_id=sheet_id,
313
+ dimension=Dimension.COLUMNS,
314
+ start_index=col_no - 1,
315
+ end_index=col_no
316
+ ),
317
+ properties=DimensionProperties(
318
+ pixel_size=width
319
+ ),
320
+ fields=FieldMask.PIXEL_SIZE
321
+ ).dict()
322
+
323
+ @staticmethod
324
+ def set_row_height(sheet_id: int, row_no: int, height: int) -> dict:
325
+ return UpdateDimensionProperties(
326
+ range=DimensionRange(
327
+ sheet_id=sheet_id,
328
+ dimension=Dimension.ROWS,
329
+ start_index=row_no - 1,
330
+ end_index=row_no
331
+ ),
332
+ properties=DimensionProperties(
333
+ pixel_size=height
334
+ ),
335
+ fields=FieldMask.PIXEL_SIZE
336
+ ).dict()
337
+
338
+ @staticmethod
339
+ def set_standard_cell_dimensions(sheet_id: int, rows: int, columns: int) -> tuple[dict, dict]:
340
+ return UpdateDimensionProperties(
341
+ range=DimensionRange(
342
+ sheet_id=sheet_id,
343
+ dimension=Dimension.ROWS,
344
+ start_index=0,
345
+ end_index=rows
346
+ ),
347
+ properties=DimensionProperties(pixel_size=21),
348
+ fields=FieldMask.PIXEL_SIZE
349
+ ).dict(), UpdateDimensionProperties(
350
+ range=DimensionRange(
351
+ sheet_id=sheet_id,
352
+ dimension=Dimension.COLUMNS,
353
+ start_index=0,
354
+ end_index=columns
355
+ ),
356
+ properties=DimensionProperties(pixel_size=100),
357
+ fields=FieldMask.PIXEL_SIZE
358
+ ).dict()
359
+
360
+ @staticmethod
361
+ def add_dimension_group(sheet_id: int, dimension: Dimension, start_index: int, end_index: int) -> dict:
362
+ """
363
+ Indexes are zero-based and inclusive [start_index, end_index].
364
+ """
365
+ return AddDimensionGroup(
366
+ range=DimensionRange(
367
+ sheet_id=sheet_id,
368
+ dimension=dimension,
369
+ start_index=start_index,
370
+ end_index=end_index + 1
371
+ )
372
+ ).dict()
373
+
374
+ @staticmethod
375
+ def delete_dimension_group(sheet_id: int, dimension: Dimension, start_index: int, end_index: int) -> dict:
376
+ """
377
+ Indexes are zero-based and inclusive [start_index, end_index].
378
+ """
379
+ return DeleteDimensionGroup(
380
+ range=DimensionRange(
381
+ sheet_id=sheet_id,
382
+ dimension=dimension,
383
+ start_index=start_index,
384
+ end_index=end_index + 1
385
+ )
386
+ ).dict()
387
+
388
+ @staticmethod
389
+ def delete_sheet(sheet_id: int) -> dict:
390
+ return DeleteSheet(sheet_id=sheet_id).dict()
391
+
392
+ @staticmethod
393
+ def add_sheet(
394
+ *,
395
+ sheet_id: int = None,
396
+ title: str = None,
397
+ index: int = None,
398
+ hidden: bool = None,
399
+ row_count: int = None,
400
+ column_count: int = None,
401
+ frozen_row_count: int = None,
402
+ frozen_column_count: int = None,
403
+ hide_grid_lines: bool = None,
404
+ ) -> dict:
405
+ return AddSheet(properties=SheetProperties(
406
+ sheet_id=sheet_id,
407
+ title=title,
408
+ index=index,
409
+ hidden=hidden,
410
+ grid_properties=GridProperties(
411
+ row_count=row_count,
412
+ column_count=column_count,
413
+ frozen_row_count=frozen_row_count,
414
+ frozen_column_count=frozen_column_count,
415
+ hide_grid_lines=hide_grid_lines
416
+ )
417
+ )).dict()
418
+
419
+ @staticmethod
420
+ def __split_excel_range(range_: str, return_as_dict: bool = False) -> tuple[int, int, int, int] | dict[str, int]:
421
+ if ':' in range_:
422
+ match = re.match(r"([A-Z]+)(\d+):([A-Z]+)(\d+)$", range_)
423
+ if not match:
424
+ raise ValueError(f'Unsupported range format: {range_}')
425
+ start_column, start_row, end_column, end_row = match.groups()
426
+
427
+ else:
428
+ match = re.match(r"([A-Z]+)(\d+)$", range_)
429
+ if not match:
430
+ raise ValueError(f'Unsupported range format: {range_}')
431
+ start_column, start_row = match.groups()
432
+ end_column, end_row = start_column, start_row
433
+
434
+ start_row, end_row = int(start_row), int(end_row)
435
+ start_column, end_column = ApiRequest.__get_column_index(start_column), ApiRequest.__get_column_index(end_column)
436
+ if start_row > end_row or start_column > end_column:
437
+ raise ValueError(f'Invalid range: {range_}')
438
+
439
+ if return_as_dict:
440
+ return {
441
+ 'start_row_index': start_row - 1,
442
+ 'end_row_index': end_row,
443
+ 'start_column_index': start_column - 1,
444
+ 'end_column_index': end_column
445
+ }
446
+ return start_row, end_row, start_column, end_column
447
+
448
+ @staticmethod
449
+ def __get_column_index(column_letters: str) -> int:
450
+ column_index = 0
451
+ for i, letter in enumerate(column_letters[::-1].upper()):
452
+ column_index += (ord(letter) - 64) * (26 ** i)
453
+ return column_index
@@ -0,0 +1,181 @@
1
+ from typing import TYPE_CHECKING
2
+
3
+ from google.oauth2.service_account import Credentials
4
+ from googleapiclient.discovery import build
5
+ from googleapiclient.errors import HttpError
6
+
7
+ from .spreadsheet_requests import Spreadsheet, SheetProperties
8
+
9
+ if TYPE_CHECKING:
10
+ from googleapiclient.discovery import Resource # noqa
11
+
12
+ DEFAULT_PATH_TO_CREDS = 'service_account.json'
13
+
14
+
15
+ class GoogleSheets:
16
+ @staticmethod
17
+ def build_service(path_to_creds: str = DEFAULT_PATH_TO_CREDS) -> 'Resource':
18
+ SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
19
+ try:
20
+ credentials = Credentials.from_service_account_file(path_to_creds, scopes=SCOPES)
21
+ except Exception as e:
22
+ raise e
23
+ return build('sheets', 'v4', credentials=credentials)
24
+
25
+ @staticmethod
26
+ def create_spreadsheet(
27
+ title: str,
28
+ folder_id: str = None,
29
+ editing_permissions_for_everyone: bool = False,
30
+ emails: list[str] = None,
31
+ email: str = None,
32
+ path_to_creds: str = DEFAULT_PATH_TO_CREDS,
33
+ ) -> tuple[str, str]:
34
+ """
35
+ Creates a Google Sheet and shares it with the specified emails.
36
+
37
+ Args:
38
+ title (str): Table name
39
+ folder_id (str): ID of the folder to place the table in
40
+ editing_permissions_for_everyone (bool): If True, shares the table with everyone who has the link
41
+ emails (list[str]): List of emails to share the table with
42
+ email (str): Single email to share the table with
43
+ path_to_creds (str): Path to the service account credentials JSON file
44
+
45
+ Returns:
46
+ tuple[str, str]: ID and URL of the created table respectively
47
+ """
48
+ SCOPES = ['https://www.googleapis.com/auth/drive']
49
+ credentials = Credentials.from_service_account_file(path_to_creds, scopes=SCOPES)
50
+ drive_service = build('drive', 'v3', credentials=credentials)
51
+
52
+ # Create a new Google Sheet
53
+ try:
54
+ file_metadata = {
55
+ 'name': title,
56
+ 'mimeType': 'application/vnd.google-apps.spreadsheet',
57
+ }
58
+ if folder_id:
59
+ file_metadata.update({'parents': [folder_id]})
60
+ spreadsheet_id = drive_service.files().create(body=file_metadata, fields='id').execute()["id"]
61
+ except HttpError as e:
62
+ raise e
63
+
64
+ # Share editing permissions with everyone who has a link or with the specified emails
65
+ try:
66
+ if editing_permissions_for_everyone:
67
+ permission = {
68
+ 'type': 'anyone',
69
+ 'role': 'writer'
70
+ }
71
+ drive_service.permissions().create(fileId=spreadsheet_id, body=permission, sendNotificationEmail=False).execute()
72
+ else:
73
+ if emails is None and email is not None:
74
+ emails = [email]
75
+ for email in emails:
76
+ permission = {
77
+ 'type': 'user',
78
+ 'role': 'writer',
79
+ 'emailAddress': email
80
+ }
81
+ drive_service.permissions().create(fileId=spreadsheet_id, body=permission, sendNotificationEmail=False).execute()
82
+ except HttpError as e:
83
+ raise e
84
+
85
+ return spreadsheet_id, f'https://docs.google.com/spreadsheets/d/{spreadsheet_id}'
86
+
87
+ @staticmethod
88
+ def update_spreadsheet(spreadsheet_id: str, api_requests: list[dict], service=None) -> None:
89
+ """
90
+ Updates Google Sheet with the specified API requests.
91
+
92
+ Args:
93
+ spreadsheet_id (str): ID of the table
94
+ api_requests (list[dict]): List of API requests to update the table
95
+ service (googleapiclient.discovery.Resource): Google Sheets service object
96
+ """
97
+ if service is None:
98
+ service = GoogleSheets.build_service()
99
+
100
+ try:
101
+ service.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_id, body={'requests': api_requests}).execute(num_retries=5)
102
+ except HttpError as e:
103
+ raise e
104
+
105
+ @staticmethod
106
+ def copy_sheet(source_spreadsheet_id: str, destination_spreadsheet_id: str, source_sheet_id: str = 0, service=None) -> SheetProperties:
107
+ if service is None:
108
+ service = GoogleSheets.build_service()
109
+
110
+ request = service.spreadsheets().sheets().copyTo(
111
+ spreadsheetId=source_spreadsheet_id,
112
+ sheetId=source_sheet_id,
113
+ body={'destinationSpreadsheetId': destination_spreadsheet_id}
114
+ )
115
+ try:
116
+ return request.execute(num_retries=5)
117
+ except HttpError as e:
118
+ raise e
119
+
120
+ @staticmethod
121
+ def get_spreadsheet(spreadsheet_id: str, service=None) -> Spreadsheet:
122
+ if service is None:
123
+ service = GoogleSheets.build_service()
124
+
125
+ return Spreadsheet.model_validate(service.spreadsheets().get(spreadsheetId=spreadsheet_id).execute(num_retries=5))
126
+
127
+ @staticmethod
128
+ def get_spreadsheet_range_values(spreadsheet_id: str, ranges: list[str], service=None) -> list[list[str] | list[list[str]]]:
129
+ """
130
+ Reads values from the specified ranges of the table.
131
+ IMPORTANT: If the last cells in the range are empty, they will be omitted. If all cells are empty, an empty
132
+ list will be returned for that range. However, leading empty cells are preserved and will appear in
133
+ the result
134
+
135
+ Args:
136
+ spreadsheet_id (str): ID of the table
137
+ ranges (list[str]): List of ranges to read in A1 notation
138
+ service (googleapiclient.discovery.Resource): Google Sheets service object
139
+
140
+ Returns:
141
+ list[list[str]]: List of values from the specified ranges in the same order
142
+ """
143
+ if service is None:
144
+ service = GoogleSheets.build_service()
145
+
146
+ try:
147
+ response = service.spreadsheets().values().batchGet(spreadsheetId=spreadsheet_id, ranges=ranges).execute(num_retries=5)
148
+ except HttpError as e:
149
+ raise e
150
+ else:
151
+ result = []
152
+ for value_range in response['valueRanges']:
153
+ values = value_range.get('values', [])
154
+ if not values:
155
+ result.append([])
156
+ continue
157
+
158
+ if len(values) == 1: # If range is a single row
159
+ result.append(values[0])
160
+ else:
161
+ if max([len(row) for row in values]) <= 1: # If range is a single column
162
+ result.append([(row[0] if row else '') for row in values])
163
+ else:
164
+ result.append(values)
165
+
166
+ return result
167
+
168
+ @staticmethod
169
+ def get_spreadsheet_id_from_url(url: str) -> str:
170
+ """
171
+ Extracts the ID of the spreadsheet from the URL.
172
+
173
+ Args:
174
+ url (str): URL of the table
175
+
176
+ Returns:
177
+ str: ID of the table
178
+ """
179
+ if '/edit' in url:
180
+ url = url[:url.index('/edit')]
181
+ return url.split('/')[-1]