Search code examples
pythongoogle-drive-apigoogle-docs-apigoogle-api-python-clientgoogle-developers-console

How to improve spacing in a document when adding data in key value pair using google docs API and python


How should I modify my request payload to add data as key value pair in a google docx using google docs API in python.

When I use the following payload, the alignment gets ruined.

requests = [{
   "insertText":{
      "text":"\nName of the Organization\t\t\t\tStackOverflow\nIndustry\t\t\t\tSo
ftware\nBusiness_Id\t\t\t123\n",
      "location":{
         "index":4
      }
   }
}]

Output: enter image description here

How can I align it properly so that the output is something like

Name Of the Organization        StackOverflow
Industry                        Software
Business_Id                     123

or can we put this in a table without showing the table borders?


Solution

  • In your situation, I would like to propose using a table for achieving your goal. When Docs API is used, the table can be created without borders. But unfortunately, in the current stage, I had thought that it is difficult to directly create a table using Docs API. So I had created a library for managing the table on Google Document using Docs API. In this answer, I would like to propose to achieve your goal using this library.

    Usage:

    1. Install library.

    $ pip install gdoctableapppy
    

    2. Sample script:

    docs = build('docs', 'v1', credentials=creds) # Please use your script here.
    documentId = "###" # Please set Google Document ID.
    
    values = [['Name Of the Organization', 'StackOverflow'], ['Industry', 'Software'], ['Business_Id', '123']]
    resource = {
        "oauth2": creds,
        "documentId": documentId,
        "rows": len(values),
        "columns": len(values[0]),
        "append": True,
        "values": values,
    }
    gdoctableapp.CreateTable(resource)
    resource = {
        "oauth2": creds,
        "documentId": documentId,
    }
    res = gdoctableapp.GetTables(resource)
    obj = {"color": {"color": {}}, "dashStyle": "SOLID", "width": {"magnitude": 0, "unit": "PT"}}
    requests = [{
        "updateTableCellStyle": {
            "tableCellStyle": {
                "borderBottom": obj,
                "borderTop": obj,
                "borderLeft": obj,
                "borderRight": obj,
            },
            "tableStartLocation": {
                "index": res['tables'][-1]['tablePosition']['startIndex']
            },
            "fields": "borderBottom,borderTop,borderLeft,borderRight"
        }
    }]
    docs.documents().batchUpdate(documentId=documentId, body={'requests': requests}).execute()
    

    3. Testing.

    When the above script is run, the following result can be obtained.

    enter image description here

    References: