这是可能的,请参阅下面的示例(该示例确实需要一些调整):
创建驱动器服务:
GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY)
.setServiceAccountId(confBean.getServiceAccountId()).setServiceAccountScopes("https://www.googleapis.com/auth/drive")
.setServiceAccountPrivateKeyFromP12File(new File("path to the P12File"))
.setServiceAccountUser("user@domain.com")
.build();
Drive drive = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).build();
创建电子表格:
com.google.api.services.drive.model.File file = new com.google.api.services.drive.model.File();
file.setTitle("test");
file.setMimeType("application/vnd.google-apps.spreadsheet");
Insert insert = this.drive.files().insert(file);
file = insert.execute();
创建电子表格服务:
GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY)
.setServiceAccountId(confBean.getServiceAccountId()).setServiceAccountScopes("https://spreadsheets.google.com/feeds")
.setServiceAccountPrivateKeyFromP12File(new File("path to the P12File"))
.setServiceAccountUser("user@domain.com")
.build();
SpreadsheetService service = new SpreadsheetService("MySpreadsheetIntegration-v1");
service.setOAuth2Credentials(credential);
检索工作表:
SpreadsheetService s = googleConn.getSpreadSheetService();
String spreadsheetURL = "https://spreadsheets.google.com/feeds/spreadsheets/" + file.getId();
SpreadsheetEntry spreadsheet = s.getEntry(new URL(spreadsheetURL), SpreadsheetEntry.class);
添加数据:
WorksheetFeed worksheetFeed = s.getFeed(spreadsheet.getWorksheetFeedUrl(), WorksheetFeed.class);
List<WorksheetEntry> worksheets = worksheetFeed.getEntries();
WorksheetEntry worksheet = worksheets.get(0);
URL cellFeedUrl= worksheet.getCellFeedUrl ();
CellFeed cellFeed= s.getFeed (cellFeedUrl, CellFeed.class);
CellEntry cellEntry= new CellEntry (1, 1, "aa");
cellFeed.insert (cellEntry);
另请参阅此相关问题