Estou trabalhando com a API do Google Docs para inserir uma tabela e preencher cada célula com texto. A tabela é inserida corretamente, mas quando insiro texto nas células, todo o conteúdo aparece comprimido na primeira célula, assim: minha saída
O que estou fazendo:
- Eu crio a tabela usando insertTable.
- Em seguida, busco o documento atualizado para encontrar a tabela e a estrutura da célula.
- Tento inserir texto em cada célula usando insertText.
Aqui está o código relevante que estou usando:
const insertTableWithText = async () => {
if (!docId) return;
try {
const doc = await gapi.client.docs.documents.get({ documentId: docId });
const endIndex = doc.result.body.content.reduce((max, el) => {
return el.endIndex > max ? el.endIndex : max;
}, 1);
const tableData = [
["Header 1", "Header 2"],
["Value 1", "Value 2"]
];
await gapi.client.docs.documents.batchUpdate({
documentId: docId,
resource: {
requests: [{
insertTable: {
rows: tableData.length,
columns: tableData[0].length,
location: { index: endIndex - 1 }
}
}]
}
});
await new Promise(resolve => setTimeout(resolve, 1000));
const updatedDoc = await gapi.client.docs.documents.get({ documentId: docId });
let tableElement = null;
for (let i = updatedDoc.result.body.content.length - 1; i >= 0; i--) {
if (updatedDoc.result.body.content[i].table) {
tableElement = updatedDoc.result.body.content[i];
break;
}
}
if (!tableElement) throw new Error("Table not found");
const requests = [];
tableElement.table.tableRows.forEach((row, rowIndex) => {
row.tableCells.forEach((cell, colIndex) => {
const paragraphIndex = cell.content[0].paragraph.elements[0].startIndex;
requests.push({
insertText: {
text: tableData[rowIndex][colIndex],
location: { index: paragraphIndex }
}
});
});
});
if (requests.length > 0) {
await gapi.client.docs.documents.batchUpdate({
documentId: docId,
resource: { requests }
});
}
} catch (err) {
console.error("Error inserting table with text:", err);
}
};
Problema: Em vez de cada valor ir para sua respectiva célula, todos os valores estão sendo inseridos na primeira célula, um após o outro (como se o índice de inserção fosse reutilizado ou sobreposto).
Como determino corretamente o índice para inserir texto em cada célula? Por que o texto aparece todo em uma célula, mesmo quando eu percorro células diferentes?