problem statement:- i want to update a table in google docs where my number of columns are fixed to 3, a table with 2 rows and 3 columns is already present in the doc, the code has to identify a placeholer ‘{{asas}}’ to start data entry form a CSV file.
error:-
1:- “Invalid requests[0].insertTableRow: Invalid table start location. Must specify the start index of the table.”. Details: “Invalid requests[0].insertTableRow: Invalid table start location. Must specify the start index of the table.”>
2:- after some changes in the code the data is sent to the table but updation is done only in the 1st cell of the table
according to me the code block ‘replace placeholder with actual data’ is having an issue
def update_table_data(document_id, csv_data):
service = initialize_docs_api()
document = service.documents().get(documentId=document_id).execute()
body = document.get('body', {})
content = body.get('content', [])
requests = []
table_id = None
for element in content:
if 'table' in element:
table = element['table']
for row in table['tableRows']:
for cell in row['tableCells']:
for content in cell['content']:
for element in content['paragraph']['elements']:
if 'textRun' in element and '{{asas}}' in element['textRun'].get('content', ''):
table_id = element
break
if table_id:
break
if table_id:
break
if table_id:
break
if not table_id:
print("Table with placeholder '{{asas}}' not found.")
return
table_start_index = table_id['startIndex']
num_rows_needed = len(csv_data)
# Insert the required number of rows
for _ in range(num_rows_needed):
requests.append({
'insertTableRow': {
'tableCellLocation': {
'tableStartLocation': {
'index': table_start_index`your text`
},
'rowIndex': len(table['tableRows']) - 1 # Insert before the last row
},
'insertBelow': True
}
})
# Replace the placeholder with actual data
for i, row in enumerate(csv_data):
for j, (key, cell_text) in enumerate(row.items()):
requests.append({
'insertText': {
'location': {
'index': table_start_index + i * len(row) + j # Calculate the index for the cell
},
'text': cell_text
}
})
# Execute the requests
if requests:
body = {'requests': requests}
response = service.documents().batchUpd`your text`ate(documentId=document_id, body=body).execute()
print('Table updated:', response.get('replies'))
updating the data in all the rows and columns of the table
Shivansh Maheshwari is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.