前言
我亲爱的领导又又给我安排了一项任务,
希望开发一个功能将我们数据库中数据,上传到Google Sheets,随时读取变更内容后更新回数据库。
这个Google Sheets可以理解为在线Excel。
接收到任务的我之前没有开发过在Google 开发平台上集成api。
我只能硬着头皮开发,顺便说说我的开发思路,
第一步:我需要先找开发者文档
第二步:理解文档,
第三部:写一个简单的例子
Sheets Api开发文档
历经千辛万苦,我终于找到了这个开发文档:(需要翻墙)
https://developers.google.com/sheets/api/quickstart/java
英文文档,说实话就很棒,我一遍猜测一遍使用谷歌翻译理解文档内容
1.需要java1.8以上版本(没关系,我的就是1.8)
2.需要Gradle (实验后发现Maven也可以)
3.创建一个项目 和 开启Api
4.创建一个凭证
创建项目,开启Api
创建说明:
https://developers.google.com/workspace/guides/create-project
点击这里先创建一个项目,
再进入Api设置
选择你要使用的API,我们当然是Googel sheets
最后开启这个api
创建凭据
这里根据各自的业务需求选择
这里需要注意一个问题:如果选择OAuth需要设定一个回调地址
因为第一次请求会做一个校验,googel会返回给你一个code。
最后我再下载创建好的凭据
这样我们的前期准备工作就完成了
代码
首先我们可以根据下面给的例子搭建一个demo
maven
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.30.4</version>
</dependency>
<dependency>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client-jetty</artifactId>
<version>1.30.6</version>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-sheets</artifactId>
<version>v4-rev581-1.25.0</version>
</dependency>
demo
这里是只是将api 文档中SheetsQuickstart 改为GoogleSheetsUtil
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.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.sheets.v4.Sheets;
import com.google.api.services.sheets.v4.SheetsScopes;
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.Collections;
import java.util.List;
public class GoogleSheetsUtil {
private static final String APPLICATION_NAME = "invault";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final String TOKENS_DIRECTORY_PATH = "tokens";
/**
* 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_READONLY);
private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
/**
* Creates an authorized Credential object.
* @param HTTP_TRANSPORT The network HTTP Transport.
* @return An authorized Credential object.
* @throws IOException If the credentials.json file cannot be found.
*/
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
// Load client secrets.
InputStream in = GoogleSheetsUtil.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();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
/**
* Prints the names and majors of students in a sample spreadsheet:
* https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
*/
public static void main(String... args) throws IOException, GeneralSecurityException {
// Build a new authorized API client service.
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
final String spreadsheetId = "1CJ9oaHk_gzKrEcSyYrzXUddrY3pYC15rmZkBoh0N5Gw";
final String range = "Sheet1!A2:F10";
Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
ValueRange response = service.spreadsheets().values()
.get(spreadsheetId, range)
.execute();
List<List<Object>> values = response.getValues();
if (values == null || values.isEmpty()) {
System.out.println("No data found.");
} else {
System.out.println("Name, Major");
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));
}
}
}
}
凭据
按照代码中的InputStream的路劲,我将下载后的凭据,改名为credentials.json然后放入
选择文档
最后我们选择要读取的文档id-即spreadsheetId
例如我创建的文档
接着选择读取范围
range这里改成你表格名称,例如我的就是原始的Sheet1
A2:F10 代表你要读取的范围