在Java中存储Google Sheets API响应的数组可以通过以下步骤实现:
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.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;
public class GoogleSheetsExample {
private static final String APPLICATION_NAME = "Google Sheets Example";
private static final String SPREADSHEET_ID = "your-spreadsheet-id";
private static final String RANGE = "Sheet1!A1:C3"; // 读取的范围
public static void main(String[] args) {
try {
Sheets sheetsService = GoogleSheetsService.createSheetsService();
// 读取数据
ValueRange response = sheetsService.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 {
Object[][] dataArray = new Object[values.size()][];
for (int i = 0; i < values.size(); i++) {
List<Object> row = values.get(i);
dataArray[i] = row.toArray(new Object[0]);
}
// 打印数组内容
for (Object[] row : dataArray) {
System.out.println(Arrays.toString(row));
}
}
} catch (IOException | GeneralSecurityException e) {
e.printStackTrace();
}
}
}
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.services.sheets.v4.Sheets;
import com.google.api.services.sheets.v4.SheetsScopes;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;
public class GoogleSheetsService {
private static final String CREDENTIALS_FILE_PATH = "path/to/credentials.json";
public static Sheets createSheetsService() throws IOException, GeneralSecurityException {
GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(CREDENTIALS_FILE_PATH))
.createScoped(Collections.singleton(SheetsScopes.SPREADSHEETS));
return new Sheets.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
}
请注意,上述代码中的your-spreadsheet-id
应替换为您要读取的Google Sheets的ID,path/to/credentials.json
应替换为您的凭据文件的路径。
这样,您就可以使用Google Sheets API读取数据并将其存储到Java中的数组中了。
领取专属 10元无门槛券
手把手带您无忧上云