I'm sorry that I'm asking too many Google docs related questions but I'm trying to make my document creation more generic and it seems very complex Here, I'm trying to create dynamic table using google docs API but there are some issues which I'm unable to resolve.
def create_table(row, column, table_index):
table_body = {
"insertTable":
{
"rows": row,
"columns": column,
"location":
{
"index": table_index
}
}
}
return table_body
def insert_table_data(row, column, text):
table_data = []
index = 0
for i in range(row):
inp_text = text[i]
for j in range(column):
index += 5
insert_value = {
"insertText":
{
"text": inp_text[j],
"location":
{
"index": index
}
}
}
table_data.append(insert_value)
index = 0
print(table_data)
return table_data
request = []
file_id = ######
requests.append(create_table(2, 2, 1))
text = [['Name', 'XYZ'], ['Industry', 'Software']]
requests.append(insert_table_data(2, 2, text))
docs.documents().batchUpdate(documentId=file_id, body={'requests': requests}).execute()
Here, I'm trying to create 2*2 table and insert the text
data. For cell indexing, I followed the following approach (I took it from Tanaike's answer)
I'm unable to change the index when row is changing. I'm getting the following payload for the table content.
[
{
"insertText":{
"text":"Name",
"location":{
"index":5
}
}
},
{
"insertText":{
"text":"XYZ",
"location":{
"index":10
}
}
},
{
"insertText":{
"text":"Industry",
"location":{
"index":5
}
}
},
{
"insertText":{
"text":"Software",
"location":{
"index":10
}
}
}
]
As stated in Tanaike's tutorial,
For the row, the index is required to set every 5 index. For the column, the index is required to set every 2 index.
Note:
def insert_table_data(row, column, text):
table_data = []
index = 0
for i in reversed(range(row)):
inp_text = text[i]
rowIndex = (i+1)*5
for j in reversed(range(column)):
index = rowIndex + (j*2)
insert_value = {
"insertText":
{
"text": inp_text[j],
"location":
{
"index": index
}
}
}
table_data.append(insert_value)
print(table_data)
return table_data
{
"insertText":{
"text":"Software",
"location":{
"index":12
}
}
},
{
"insertText":{
"text":"Industry",
"location":{
"index":10
}
}
},
{
"insertText":{
"text":"XYZ",
"location":{
"index":7
}
}
},
{
"insertText":{
"text":"Name",
"location":{
"index":5
}
}
}