Reputation: 1678
I want to create new sheet in google sheet document using Java API v4. I tested this code:
Sheets service = getSheetsService();
Spreadsheet sheet = new Spreadsheet();
SpreadsheetProperties properties = new SpreadsheetProperties();
properties.setTitle("new SpreadSheetTitle");
sheet.setProperties(properties);
Spreadsheet response = service.spreadsheets().create(sheet)
.execute();
But when I open the document I don't see new page. What is the proper way to implement this?
P.S
I managed to create this:
List<List<Object>> writeData = new ArrayList<>();
List<Object> dataRow = new ArrayList<>();
dataRow.add("data 1 " + timestamp);
dataRow.add("data 2 " + timestamp);
dataRow.add("data 3 " + timestamp);
dataRow.add("data 4 " + timestamp);
dataRow.add("data 5 " + timestamp);
writeData.add(dataRow);
requests.add(new Request().setAddSheet(new AddSheetRequest()
.setProperties(new SheetProperties().setTitle("scstc"))));
BatchUpdateSpreadsheetRequest body
= new BatchUpdateSpreadsheetRequest().setRequests(requests);
BatchUpdateSpreadsheetResponse response = service.spreadsheets().batchUpdate(spreadsheetId, body).execute();
I can create empty sheet but how I can inset test data?
Upvotes: 4
Views: 2985
Reputation: 543
Sheets sheetsService = SheetsServiceUtil.getSheetsService();
List<Request> requests = new ArrayList<>();
requests.add(new Request().setAddSheet(new AddSheetRequest().setProperties(new SheetProperties()
.setTitle("NEW_TAB"))));
BatchUpdateSpreadsheetRequest body = new BatchUpdateSpreadsheetRequest().setRequests(requests);
sheetsService.spreadsheets().batchUpdate(SPREADSHEET_ID, body)
.execute();
Upvotes: 2
Reputation: 69
If you want to update or append data to an existing Sheet (Tab) inside your spreadsheet you can use the following for update:
sheetsService.spreadsheets()
.values()
.update(spreadsheetId, "NAME_OF_EXISTING_SPREADSHEET", body)
.execute();
Or this one for append:
sheetsService.spreadsheets()
.values()
.append(spreadsheetId, "NAME_OF_EXISTING_SPREADSHEET", body)
.execute();
This works only if the sheet(tab) is already created.
Upvotes: -1
Reputation: 29
You created a new tab in your document If you want to add some columns when you create it, you can do it like this:
ValueRange appendBody = new ValueRange()
.setValues(Collections.singletonList(
Arrays.asList("ColumnName1", "ColumnName2")));
getSheetsService().spreadsheets().values()
.append(SPREADSHEET_ID, "TITLE_OF_YOUR_NEW_TAB", appendBody)
.setValueInputOption("USER_ENTERED")
.setInsertDataOption("INSERT_ROWS")
.setIncludeValuesInResponse(true)
.execute();
This code just inserts data to new tab with name "TITLE_OF_YOUR_NEW_TAB"
public Sheets getSheetsService() throws IOException, GeneralSecurityException {
Credential credential = authorize();
return new Sheets.Builder(GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, credential)
.build();
}
Upvotes: 2