JAVA使用Google sheet 的API服务

和使用google drive API的方式差不多,直接上代码 (英文指导Google sheet Java Quickstart)

  • 先去注册软件生成credentials.json
  • 改build.gradle文件
    这上面两步可以去看Google drive 的API如何使用的,是一样的。json文件是可以重复使用的。(drive指导Google drive Java Quickstart)
  • 第一个function是生成service
  • 第二个function是读取sheet的数据
  • 第三个function是改变sheet的数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.sheets.v4.Sheets;
import com.google.api.services.sheets.v4.SheetsScopes;
import com.google.api.services.sheets.v4.model.GridRange;
import com.google.api.services.sheets.v4.model.UpdateValuesResponse;
import com.google.api.services.sheets.v4.model.ValueRange;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SheetsQuickstart {
private static final String APPLICATION_NAME = "Google Sheets API Java Quickstart";
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
private static final String TOKENS_DIRECTORY_PATH = "sheettokens";

/**
* Global instance of the scopes required by this quickstart.
* If modifying these scopes, delete your previously saved tokens/ folder.
*/
private static final List<String> SCOPES = Collections.singletonList(SheetsScopes.SPREADSHEETS);
private static final String CREDENTIALS_FILE_PATH = "/credentials.json";

private static Credential this_token = null;
private static Sheets service = null;

/**
* init the sheet.
* @throws IOException If the credentials.json file cannot be found.
*/
public SheetsQuickstart() throws IOException, GeneralSecurityException {

final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();

// Load client secrets.
InputStream in = SheetsQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();

this_token = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");

service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, this_token)
.setApplicationName(APPLICATION_NAME)
.build();
}


/**
* Prints the names and majors of students in a sample spreadsheet:
* https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
*/
public static List<String> run(String file) throws IOException, GeneralSecurityException {
// Build a new authorized API client service.

final String spreadsheetId = file;
final String range = "A2:C";

ValueRange response = service.spreadsheets().values()
.get(spreadsheetId, range)
.execute();
List<List<Object>> values = response.getValues();

List<String> ans = new ArrayList<>();
if (values == null || values.isEmpty()) {
System.out.println("No data found.");
} else {
for (List row : values) {
// Print columns A and E, which correspond to indices 0 and 4.
//System.out.printf("%s, %s\n", row.get(0), row.get(4));
ans.add(row.get(0).toString());
//System.out.printf("%s\n", row.get(0));
}
}
return ans;
}


public static UpdateValuesResponse updateValues(String spreadsheetId,
String range,
String valueInputOption,
List<List<Object>> values)
throws IOException {

UpdateValuesResponse result =null;
try {
// Updates the values in the specified range.
ValueRange body = new ValueRange()
.setValues(values);
result = service.spreadsheets().values().update(spreadsheetId, range, body)
.setValueInputOption(valueInputOption)
.execute();
System.out.printf("%d cells updated.\n", result.getUpdatedCells());
} catch (GoogleJsonResponseException e) {
// TODO(developer) - handle error appropriately
GoogleJsonError error = e.getDetails();
if (error.getCode() == 404) {
System.out.printf("Spreadsheet not found with id '%s'.\n",spreadsheetId);
} else {
throw e;
}
}
return result;
}
}