1. 사전 준비 사항
🔐 A. 구글 클라우드 프로젝트 생성 & API 사용 설정
- Google Cloud Console 접속
- 새 프로젝트 생성
- Google Sheets API & Google Drive API 활성화
- 서비스 계정(Service Account) 생성
- 서비스 계정에 JSON 키 발급
2. 인증 정보 등록
Spring Boot 프로젝트에서 사용할 수 있도록, 발급받은 JSON 파일을 프로젝트 리소스 폴더에 저장 (src/main/resources/credentials.json 등)
✅ 3. Google Sheet 공유 설정
스프레드시트를 서비스 계정 이메일 주소와 공유해야 합니다.
예:
서비스 계정 이메일이 my-service-account@my-project.iam.gserviceaccount.com 이라면
구글 시트 공유 설정에서 이 계정을 편집 권한으로 추가해야 합니다!
✅ 4. 코드 예시: Java에서 한 줄 추가하기
public class GoogleSheetAppender {
private static final String APPLICATION_NAME = "My Spring Sheet Writer";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; // resources 경로
public static Sheets getSheetsService() throws Exception {
GoogleCredentials credentials;
try (InputStream in = GoogleSheetAppender.class.getResourceAsStream(CREDENTIALS_FILE_PATH)) {
credentials = GoogleCredentials.fromStream(in)
.createScoped(List.of("https://www.googleapis.com/auth/spreadsheets"));
}
return new Sheets.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JSON_FACTORY,
new HttpCredentialsAdapter(credentials))
.setApplicationName(APPLICATION_NAME)
.build();
}
public static void appendRow(String spreadsheetId, String range, List<Object> rowData) throws Exception {
Sheets sheetsService = getSheetsService();
ValueRange appendBody = new ValueRange().setValues(List.of(rowData));
sheetsService.spreadsheets().values()
.append(spreadsheetId, range, appendBody)
.setValueInputOption("RAW")
.execute();
}
}
(사용예제)
GoogleSheetAppender.appendRow(
"your-spreadsheet-id", // 시트 ID
"Sheet1!A1", // 추가할 범위
List.of("홍길동", "테스트 메시지", "2025-04-10")
);