javascriptreactjsgoogle-docsgoogle-docs-api

Google Docs API: Text from insertText appears all in the first cell of table — how to correctly insert text into each cell? Using React


I'm working with the Google Docs API to insert a table and then populate each cell with text. The table gets inserted correctly, but when I insert text into the cells, all the content appears squished into the first cell, like this: my output

What I'm doing:

  1. I create the table using insertTable.
  2. Then I fetch the updated document to find the table and cell structure.
  3. I attempt to insert text into each cell using insertText.

Here’s the relevant code I’m using:

    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);
  }
};

Problem: Instead of each value going into its respective cell, all the values are being inserted into the first cell, one after another (as if the insert index is reused or overlapping).

How do I properly determine the correct index to insert text into each individual cell? Why is text appearing all in one cell even though I loop through different cells?


Solution

  • This thread might be useful for putting the values into the cells in the created table on Google Docs. Ref (Author: me)When your showing script is modified by this report, how about the following modification?

    Modified script:

    const docId = "###"; // Please set your Doc ID.
    const endIndex = 2; // Please set your endIndex
    
    // This is from your showing script.
    const tableData = [
      ["Header 1", "Header 2"],
      ["Value 1", "Value 2"]
    ];
    
    const tableIndex = endIndex - 1; // This is from your script.
    
    const maxLen = Math.max(...tableData.map(r => r.length));
    const tableIndex = endIndex - 1;
    let index = tableIndex + 5;
    const cellValues = tableData.flatMap((r, i) => {
      const rowIndex = index + (i == 0 ? 0 : 3) - 1;
      const o = r.map((c, j) => {
        const idx = rowIndex + j * 2;
        const obj = { insertText: { text: c, location: { index: idx } } };
        index = idx + 1;
        return obj;
      });
      if (r.length < maxLen) {
        index += (maxLen - r.length) * 2;
      }
      return o;
    }).reverse();
    const requests = [
      { insertTable: { rows: tableData.length, columns: tableData[0].length, location: { index: tableIndex } } },
      ...cellValues
    ];
    
    await gapi.client.docs.documents.batchUpdate({
      documentId: docId,
      resource: { requests }
    });
    

    In this modification, the creation of table and the insersion of cell values can be run by one API call.

    Testing:

    When endIndex is 2, the following result is obtained.

    enter image description here

    References: