Finding Table Start Location Index using Google Docs API

Viewed 900

I want to make a InsertTableRow Request via Docs API and it requires a TableStartLocation. I used

var tableName = table[0];
foreach (var element in document.Body.Content)
if (element.Table != null)
{
   var checkTable = element.Table.TableRows[0].TableCells[0].Content[0].Paragraph.Elements[0]
                            .TextRun.Content.TrimEnd('\n'); //Get Text Value in first cell of the table
                        
   if (tableName.Equals(checkTable)) // Check if the table is the table that I want to add rows
      {
          Console.WriteLine("Add Table Row");
          TableUpdateRequest(ref requests, table, element.StartIndex); // Using element(StructuralElement) to get StartIndex
          break;
      }
}

To find all table in a document and tried to use the element.StartIndex as Table Start Location but i got: Google.GoogleApiException : Google.Apis.Requests.RequestError Invalid requests[5].insertTableRow: Invalid table start location. Must specify the start index of the table. [400]

What is a suitable index for Table Start Location?

1 Answers

The tableStartLocation is necessary to identify the correct table

A way to retrieve it is e.g. with documents.get. To narrow down the results you can specify fields, e.g. body/content(startIndex,table).

This will return you a resource of the type

{
  "body": {
    "content": [
      {},
      {
        "startIndex": 1
      },
      {
        "startIndex": 2,
        "table": {
          "rows": 4,
          "columns": 3,
          "tableRows": [
            {
             ...

In other words: You know now that your tableStartLocation is 2 - same as the table's startIndex.

Sample

  var resource = { "requests": [
    {
      "insertTableRow": {
        "tableCellLocation": {
          "tableStartLocation": {
            "index": 2
          }
        },
        "insertBelow": false
      }
    }
  ]
                 }
  Docs.Documents.batchUpdate(resource, documentId);

Now, depending on your document, you might have several tables and might want to compare names etc. before deciding which is the start index of the correct able.

Related