I’m trying to populate a table in Google Docs using data from a CSV file. The table has a fixed structure with 3 columns and initially contains 2 rows. I need to locate the table by finding a specific placeholder {{marker}} within it.
I’m running into two main problems:
- Getting this error:
"Invalid requests[0].insertTableRow: Invalid table start location. Must specify the start index of the table." - When I fix the above issue, only the first cell gets updated instead of all cells
I think the problem is in my data replacement logic. Here’s my current approach:
def populate_doc_table(doc_id, file_data):
api_service = setup_google_docs()
doc = api_service.documents().get(documentId=doc_id).execute()
doc_body = doc.get('body', {})
elements = doc_body.get('content', [])
operations = []
target_table = None
for item in elements:
if 'table' in item:
current_table = item['table']
for table_row in current_table['tableRows']:
for table_cell in table_row['tableCells']:
for cell_content in table_cell['content']:
for text_element in cell_content['paragraph']['elements']:
if 'textRun' in text_element and '{{marker}}' in text_element['textRun'].get('content', ''):
target_table = text_element
break
if target_table:
break
if target_table:
break
if target_table:
break
if not target_table:
print("Cannot find table containing placeholder '{{marker}}'")
return
start_position = target_table['startIndex']
required_rows = len(file_data)
# Add necessary rows to table
for _ in range(required_rows):
operations.append({
'insertTableRow': {
'tableCellLocation': {
'tableStartLocation': {
'index': start_position
},
'rowIndex': len(current_table['tableRows']) - 1
},
'insertBelow': True
}
})
# Fill cells with CSV content
for row_num, data_row in enumerate(file_data):
for col_num, (field, value) in enumerate(data_row.items()):
operations.append({
'insertText': {
'location': {
'index': start_position + row_num * len(data_row) + col_num
},
'text': value
}
})
# Apply all changes
if operations:
request_body = {'requests': operations}
result = api_service.documents().batchUpdate(documentId=doc_id, body=request_body).execute()
print('Table modification complete:', result.get('replies'))
I need all rows and columns in the table to be properly filled with the CSV data. What am I doing wrong with the index calculation?