编程语言
首页 > 编程语言> > java – 使用一个请求创建工作表并更新数据

java – 使用一个请求创建工作表并更新数据

作者:互联网

我想通过一个api调用实现Google sheet api请求.

我设法实现了这段代码:

List<Request> requests = new ArrayList<>();

        List<CellData> values = new ArrayList<>();

        values.add(new CellData()
            .setUserEnteredValue(new ExtendedValue()
                .setStringValue("Hello World!")));

        requests.add(new Request().setAddSheet(new AddSheetRequest()
            .setProperties(new SheetProperties()
                .setTitle("scstc")))
            .setUpdateCells(new UpdateCellsRequest()
                .setStart(new GridCoordinate()
                    .setSheetId(0)
                    .setRowIndex(0)
                    .setColumnIndex(0))
                .setRows(Arrays.asList(
                    new RowData().setValues(values)))
                .setFields("userEnteredValue,userEnteredFormat.backgroundColor"))
        );

        BatchUpdateSpreadsheetRequest body = new BatchUpdateSpreadsheetRequest().setRequests(requests);

        BatchUpdateSpreadsheetResponse response = service.spreadsheets().batchUpdate(spreadsheetId, body).execute();

但我得到错误:

400 Bad Request
{
  "code" : 400,
  "errors" : [ {
    "domain" : "global",
    "message" : "Invalid value at 'requests[0]' (oneof), oneof field 'kind' is already set. Cannot set 'updateCells'",
    "reason" : "badRequest"
  } ],
  "message" : "Invalid value at 'requests[0]' (oneof), oneof field 'kind' is already set. Cannot set 'updateCells'",
  "status" : "INVALID_ARGUMENT"
}
    at com.google.sheet.impl.GoogleSheetBasicTest1_____1.hello(GoogleSheetBasicTest1_____1.java:133)

你是如何解决这个问题的?

解决方法:

每个Request对象只能在其中设置一个值.您正在设置两个值:

requests.add(new Request()
            .setAddSheet(...)
            .setUpdateCells(...));

您需要使用两个请求对象,而不是执行上述操作:

requests.add(new Request().setAddSheet(...));
requests.add(new Request().setUpdateCells(...));

标签:java,google-api,google-sheets,google-sheets-api
来源: https://codeday.me/bug/20190611/1218297.html