📅  最后修改于: 2023-12-03 15:36:39.413000             🧑  作者: Mango
Google表格是一个强大的云计算工具,可以用于管理数据、创建图表和共享信息。如果您需要以编程方式操作谷歌表格数据,您可以使用Java开发的Google应用脚本。
在开发Google应用脚本之前,您需要创建一个Google账户、一个Google Drive授权,并在Google开发者控制台创建一个新项目。在另外的终端中安装Java 8或更高版本。
创建一个名为getting-started-java
的新Maven项目,并更新pom.xml文件以包含以下依赖项。
<dependencies>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-sheets</artifactId>
<version>v4-rev493-1.23.0</version>
</dependency>
<dependency>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client-jetty</artifactId>
<version>1.25.0</version>
</dependency>
</dependencies>
在Google开发者控制台中启用Google API服务和Sheets API。然后从github下载客户端ID和应用程序密钥,将它们存储在本地计算机上的任何适当的位置。
public class SheetsQuickstart {
private static final String APPLICATION_NAME = "Google Sheets API Java Quickstart";
private static final JsonFactory JSON_FACTORY = com.google.api.client.json.jackson2.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";
private static final String SPREADSHEET_ID = "<your-spreadsheet-id>";
/**
* Creates an authorized Credential object.
* @param httpTransport 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 httpTransport) throws IOException {
// 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(
httpTransport, 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");
}
public static void main(String[] args) throws IOException, GeneralSecurityException {
// Build a new authorized API client service.
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
// Prints the name and values of every column.
String range = "Sheet1!A1:Z";
ValueRange response = service.spreadsheets().values()
.get(SPREADSHEET_ID, 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 B, which correspond to indices 0 and 1.
System.out.printf("%s, %s\n", row.get(0), row.get(1));
}
}
}
}
您现在可以运行您的Java应用程序,从谷歌表格(例如<your-spreadsheet-id>
)中检索数据并将其显示在控制台上。
在项目根目录下运行以下命令行:
mvn compile exec:java -Dexec.mainClass=com.example.sheets.SheetsQuickstart
现在,您已经成功地创建了一个Java项目,其中包括使用Google应用脚本获取价值谷歌表的代码。