본문 바로가기
Spring-boot

Spring-boot Google Sheets API #2 연동

by 조민욱 2024. 4. 25.

일전에 https://minuk22.tistory.com/89 여기서

Google Sheets API 생성과 시트에 공유를 통한 작업을 진행하였다

이제 Spring - boot를 활용해서 데이터가 들어왔을 때

시트에 입력값을 넣어보는 작업을 해보자

 

1. 기존에 받았던 .json 파일을 google.json 파일명으로 변경

2. resources => googlesheet => 내부에 파일을 저장 

3. 의존성 주입 (gradle)

implementation 'com.google.apis:google-api-services-sheets:v4-rev516-1.23.0'
implementation 'com.google.auth:google-auth-library-oauth2-http:0.20.0'

4. GoogleController 파일추가 

@RestController
@RequestMapping("/google")
@RequiredArgsConstructor
public class GoogleController {

    private final GoogleService googleService;

    private static final String SPREADSHEET_ID = "스프레드 시트 URL 주소"; // 1. 기존에 스프레스 시트id를 복사해둔곳을 여기에 저장해둔다.
    private static final String RANGE = "A1"; // 2. 작성할 행을 입력

    @PostMapping("/write")
    public ResponseEntity<String> writeToSheet(@RequestParam String word) {
        try {
            // 3. 데이터를 스프레드시트에 쓰기 위해 전달되는 형식
            // 행과 열에 데이터를 매핑하기 위함
            List<List<Object>> values = List.of(Collections.singletonList(word));

            // 4. 서비스 로직 호출 
            googleService.writeToSheet(SPREADSHEET_ID, RANGE, values);
            return ResponseEntity.ok("Data written successfully to the spreadsheet: " + word);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError().body("Failed to write data: " + e.getMessage());
        }
    }
}

 

 

 

 

5.GoogleService 를 작업해준다.

@Service
public class GoogleService {

    private static final Logger logger = LoggerFactory.getLogger(GoogleService.class); // Google Sheets와 상호작용하기 위한 메서드를 포함
    private static final String APPLICATION_NAME = "Google Sheets Application"; // Google Sheets 애플리케이션의 이름을 나타냄
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); // 상수는 JSON 데이터를 처리하기 위한 JsonFactory 인스턴스를 제공
    private static final String CREDENTIALS_FILE_PATH = "/googlesheet/google.json"; // 인증에 사용되는 JSON 파링릐 경로를 지정
    private Sheets sheetsService;

	// 현재의 메소드는 Sheets 인스턴스를 얻는 데 사용 
    private Sheets getSheetsService() throws IOException, GeneralSecurityException {
        if (sheetsService == null) {
            GoogleCredentials credentials = GoogleCredentials.fromStream(new ClassPathResource(CREDENTIALS_FILE_PATH).getInputStream())
            // Google API를 호출할 떄 필요한 권한을 지정하는 부분 , 읽기/쓰기 권한을 나타냄 
                .createScoped(Collections.singletonList("https://www.googleapis.com/auth/spreadsheets"));
            sheetsService = new Sheets.Builder(GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, new HttpCredentialsAdapter(credentials))
                .setApplicationName(APPLICATION_NAME)
                .build();
        }
        return sheetsService;
    }

    public void writeToSheet(String spreadsheetId, String range, List<List<Object>> values) {
        try {
            Sheets service = getSheetsService();
            ValueRange body = new ValueRange().setValues(values);
            UpdateValuesResponse result = service.spreadsheets().values()
                .update(spreadsheetId, range, body)
                .setValueInputOption("USER_ENTERED")
                .execute();
            logger.info("Updated rows: {}", result.getUpdatedRows());
        } catch (Exception e) {
            logger.error("Failed to write data to the spreadsheet", e);
            throw new RuntimeException("Failed to write data to the spreadsheet: " + e.getMessage(), e);
        }
    }
}

 

6. 로직 완성 후 포스트맨으로 테스트를 거쳐 성공 ! 

 

 

만약 권한 부여 관련 에러가 나오거나 시트를 위치를 찾을 수 없는 에러가 나온다면 

지금까지 했던 로직과 내용을 다시 확인 !

'Spring-boot' 카테고리의 다른 글

spring-boot 업로드 2  (1) 2024.06.13
spring-boot 엑셀 업로드  (1) 2024.06.12
Spring-boot Google Sheets API #1  (0) 2024.04.25
Spring-boot 로그 기록 남겨두기  (0) 2024.04.19
aws 키 페어 생성하기  (0) 2024.04.19