使用Google表格API v4更改行的背景颜色

时间:2018-05-03 18:17:04

标签: java google-spreadsheet-api google-sheets-api

我正在尝试更改Google电子表格中第一行(标题)的背景颜色。基于几个小时的研究和阅读,我想出了以下代码:

Request updateBackgroundColorRequest = new Request();
UpdateCellsRequest updateCellsRequest = new UpdateCellsRequest();

CellFormat cellFormat = new CellFormat();
Color color = new Color();
color.setRed((float) 246);
color.setGreen((float) 178);
color.setBlue((float) 107);

cellFormat.setBackgroundColor(color);

GridRange gridRange = new GridRange();
gridRange.setStartRowIndex(0);
gridRange.setEndRowIndex(1);
gridRange.setStartColumnIndex(0);
gridRange.setEndColumnIndex(14);
updateCellsRequest.setRange(gridRange);

String field = "userEnteredFormat.backgroundColor";
updateCellsRequest.setFields(field);
updateBackgroundColorRequest.setUpdateCells(updateCellsRequest);

requestList.add(updateBackgroundColorRequest);
batchUpdateSpreadsheetRequest.setRequests(requestList);

Spreadsheets.BatchUpdate batchUpdate = service.spreadsheets()
    .batchUpdate(spreadsheetId, batchUpdateSpreadsheetRequest);
batchUpdate.execute();

然而,虽然我能够成功执行此代码(API不会返回任何错误),但背景颜色根本不会改变(我希望它会变为橙色但仍保持白色)。

我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

陷入同样的​​问题。谢谢你的代码!这对我有很大帮助!

所以问题就在这里。

updateBackgroundColorRequest.setUpdateCells(updateCellsRequest);

您需要 RepeateCellRequest 类,而不是 UpdateCellRequest

简单的请求集将类似于

requestList.add(new Request().setRepeatCell(
   new RepeatCellRequest().
   setCell(cellData).
   setRange(gridRange).
   setFields("*")));

我所有的代码如下:

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

CellFormat cellFormat = new CellFormat(); //setting cell color
Color color = new Color();
color.setRed(246f);
color.setGreen(178f);
color.setBlue(107f);

cellFormat.setBackgroundColor(color);

CellData cellData = new CellData();
cellData.setUserEnteredFormat(cellFormat);

GridRange gridRange = new GridRange(); //setting grid that we will paint
gridRange.setSheetId(1115615634); //you can find it in your URL - param "gid"
gridRange.setStartRowIndex(0);
gridRange.setEndRowIndex(1);
gridRange.setStartColumnIndex(0);
gridRange.setEndColumnIndex(14);

requestList.add(new Request().setRepeatCell(new RepeatCellRequest().setCell(cellData).setRange(gridRange).setFields("userEnteredFormat.backgroundColor")));

BatchUpdateSpreadsheetRequest batchUpdateSpreadsheetRequest = new BatchUpdateSpreadsheetRequest();
batchUpdateSpreadsheetRequest.setRequests(requestList);

final Sheets.Spreadsheets.BatchUpdate batchUpdate = sheetsService.
        spreadsheets().batchUpdate("yourSpreadSheetId - find it in URL", batchUpdateSpreadsheetRequest);

batchUpdate.execute();