создать таблицу с помощью API слайдов Google

Я пытаюсь создать новый слайд, содержащий таблицу с некоторыми данными, используя API Google Slides. Я получаю неверную ошибку полезной нагрузки JSON.

Я попытался создать функцию, которая выполняет запрос новой таблицы.

def make_table_obj(self, data):
    '''make a table object to be added to a slide'''
    keys = [key for key in data[0].keys()]
    return {
        "objectId": gen_id(),
        "pageType": "SLIDE",
        "pageElements": [
            {"elementGroup": {
                "table": {
                    "rows": len(data),
                    "columns": len(data[0].keys()),
                    "tableRows": [
                        [
                            {
                                "text": data[i][keys[k]],
                                "location": {"rowIndex": i, "columnIndex": k}
                            } for k in range(int(len(keys)))
                        ]
                        for i in range(int(len(data)))
                        ]}
        }}]
        }

Вот несколько примеров данных, которые помогут мне

[{'_id': 'Customer Service',
  'metric1': 239.0,
  'metric2': 1875.0},
 {'_id': 'Order',
  'metric1': 2846.0,
  'metric2': 5171.0},
 {'_id': 'Checkout',
  'metric1': 1789.0,
  'metric2': 2446.0}]

Функция выдает запрос, который мне нужен (я думаю), но я получаю эту ошибку.

googleapiclient.errors.HttpError: <HttpError 400 when requesting https://slides.googleapis.com/v1/presentations/<presentationId>:batchUpdate?alt=json returned "Invalid value at 'requests[1].create_shape.shape_type' (type.googleapis.com/google.apps.slides.v1.Shape.Type), "Table"
Invalid JSON payload received. Unknown name "rows" at 'requests[1].create_shape.element_properties': Cannot find field.
Invalid JSON payload received. Unknown name "columns" at 'requests[1].create_shape.element_properties': Cannot find field.
Invalid JSON payload received. Unknown name "tableRows" at 'requests[1].create_shape.element_properties': Cannot find field.". Details: "[{'@type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'field': 'requests[1].create_shape.shape_type', 'description': 'Invalid value at \'requests[1].create_shape.shape_type\' (type.googleapis.com/google.apps.slides.v1.Shape.Type), "Table"'}, {'field': 'requests[1].create_shape.element_properties', 'description': 'Invalid JSON payload received. Unknown name "rows" at \'requests[1].create_shape.element_properties\': Cannot find field.'}, {'field': 'requests[1].create_shape.element_properties', 'description': 'Invalid JSON payload received. Unknown name "columns" at \'requests[1].create_shape.element_properties\': Cannot find field.'}, {'field': 'requests[1].create_shape.element_properties', 'description': 'Invalid JSON payload received. Unknown name "tableRows" at \'requests[1].create_shape.element_properties\': Cannot find field.'}]}]">

Вот полный запрос, который я отправляю.

[
 {
  "objectId": "id-1617143529-776043",
  "pageType": "SLIDE",
  "pageElements": [
   {
    "elementGroup": {
     "table": {
      "rows": 23,
      "columns": 3,
      "tableRows": [
       [
        {
         "text": "Customer Service",
         "location": {
          "rowIndex": 0,
          "columnIndex": 0
         }
        },
        {
         "text": 239.0,
         "location": {
          "rowIndex": 0,
          "columnIndex": 1
         }
        },
        {
         "text": 1875.0,
         "location": {
          "rowIndex": 0,
          "columnIndex": 2
         }
        }
       ],
       [
        {
         "text": "Order",
         "location": {
          "rowIndex": 1,
          "columnIndex": 0
         }
        },
        {
         "text": 2846.0,
         "location": {
          "rowIndex": 1,
          "columnIndex": 1
         }
        },
        {
         "text": 5171.0,
         "location": {
          "rowIndex": 1,
          "columnIndex": 2
         }
        }
       ],
       [
        {
         "text": "Checkout",
         "location": {
          "rowIndex": 2,
          "columnIndex": 0
         }
        },
        {
         "text": 1789.0,
         "location": {
          "rowIndex": 2,
          "columnIndex": 1
         }
        },
        {
         "text": 2446.0,
         "location": {
          "rowIndex": 2,
          "columnIndex": 2
         }
        }
       ],
      ]
     }
    }
   }
  ]
 }
]

Заранее спасибо, если вы можете помочь, я знаю, что этот вопрос слишком длинный.


person unltd_J    schedule 30.03.2021    source источник


Ответы (1)


Для создания и редактирования табличных данных следует использовать Табличные операции.

Пример тела запроса:

Примечание. Приведенный ниже запрос создает новый слайд с идентификатором id-1617139878-856039 и вставляет в него таблицу с данными.

{
  "requests": [
    {
      "createSlide": {
        "objectId": "id-1617139878-856039",
        "insertionIndex": 9,
        "slideLayoutReference": {
          "predefinedLayout": "TITLE"
        }
      }
    },
    {
      "createTable": {
        "objectId": "123456",
        "elementProperties": {
          "pageObjectId": "id-1617139878-856039"
        },
        "rows": 3,
        "columns": 3
      }
    },
    {
      "insertText": {
        "objectId": "123456",
        "cellLocation": {
          "rowIndex": 0,
          "columnIndex": 0
        },
        "text": "Customer Service"
      }
    },
    {
      "insertText": {
        "objectId": "123456",
        "cellLocation": {
          "rowIndex": 0,
          "columnIndex": 1
        },
        "text": "239.0"
      }
    },
    {
      "insertText": {
        "objectId": "123456",
        "cellLocation": {
          "rowIndex": 0,
          "columnIndex": 2
        },
        "text": "1875.0"
      }
    },
    {
      "insertText": {
        "objectId": "123456",
        "cellLocation": {
          "rowIndex": 1,
          "columnIndex": 0
        },
        "text": "Order"
      }
    },
    {
      "insertText": {
        "objectId": "123456",
        "cellLocation": {
          "rowIndex": 1,
          "columnIndex": 1
        },
        "text": "2846.0"
      }
    },
    {
      "insertText": {
        "objectId": "123456",
        "cellLocation": {
          "rowIndex": 1,
          "columnIndex": 2
        },
        "text": "2846.0"
      }
    },
    {
      "insertText": {
        "objectId": "123456",
        "cellLocation": {
          "rowIndex": 2,
          "columnIndex": 0
        },
        "text": "Checkout"
      }
    },
    {
      "insertText": {
        "objectId": "123456",
        "cellLocation": {
          "rowIndex": 2,
          "columnIndex": 1
        },
        "text": "1789.0"
      }
    },
    {
      "insertText": {
        "objectId": "123456",
        "cellLocation": {
          "rowIndex": 2,
          "columnIndex": 2
        },
        "text": "2446.0"
      }
    }
  ]
}

Вывод:

введите описание изображения здесь

Я проверил запрос здесь: Пакетное обновление Google Slide API

person Nikko J.    schedule 30.03.2021