프로그래밍 언어/JAVA, SPRING

Google SpreadSheet API와 JAVA 연동하기 #2

doomole 2023. 8. 14. 15:06
728x90

https://many.tistory.com/11에서 google에 대한 설정을 마쳤다.

이번 글에서는 java에서 코드 작성 후 api 연동까지 수행해보겠다.

 

방장은 maven spring boot 프로젝트로 라이브러리를 추가하여 개발을 수행하였다.


1. pom.xml

필요한 라이브러리들을 추가했다.

		<!-- google sheet -->
		<dependency>
			<groupId>com.google.api-client</groupId>
			<artifactId>google-api-client</artifactId>
			<version>1.25.0</version>
		</dependency>
		<dependency>
			<groupId>com.google.oauth-client</groupId>
			<artifactId>google-oauth-client</artifactId>
			<version>1.34.1</version>
		</dependency>
		<dependency>
			<groupId>com.google.apis</groupId>
			<artifactId>google-api-services-sheets</artifactId>
			<version>v4-rev612-1.25.0</version>
		</dependency>
		<dependency>
			<groupId>com.google.oauth-client</groupId>
			<artifactId>google-oauth-client-java6</artifactId>
			<version>1.21.0</version>
		</dependency>
		<dependency>
			<groupId>com.google.oauth-client</groupId>
			<artifactId>google-oauth-client-jetty</artifactId>
			<version>1.21.0</version>
		</dependency>
		<dependency>
			<groupId>com.google.api-client</groupId>
			<artifactId>google-api-client-jackson2</artifactId>
			<version>1.20.0</version>
		</dependency>

 


2. class 생성

이해를 쉽게 하기 위해 한 클래스에 모두 작성하겠다.

GoogleSheetService 라는 class를 생성해주고, 전역 변수를 선언한다.

CREDENTIALS_FILE_PATH는 아까 발급한 json 형태의 서비스 계정의 키의 경로이다. 방장은 resources 밑에 googlesheet 디렉토리 하위에 넣었다.

APPLICATION_NAME은 프로젝트의 명으로 선언했다.(해당 변수가 꼭 필요한지는 모르겠다.... 아시는 분은 댓글좀 달아주세요 ㅎㅎ)

SCOPES는 google sheet에서 수행할 동작의 범위를 지정해준다. 읽기/쓰기를 모두 수행할 거기 때문에 SPREADSHEETS로 선언했다.

import com.at.interceptor.common.util.GoogleSheetUtil;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
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.gson.GsonFactory;
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.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

public class GoogleSheetService {
	private static final String CREDENTIALS_FILE_PATH = "googlesheet/google_spread_sheet_key.json";
	private static final String APPLICATION_NAME = "google-sheet-project";
	private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
	private static final List<String> SCOPES = Collections.singletonList(SheetsScopes.SPREADSHEETS);
}

 


3. credential method

google 인증을 위한 credential 객체를 생성하는 메소드이다.

key를 읽어서 인증 객체로 생성한다.

private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT)
            throws IOException {
        ClassLoader loader = GoogleSheetService.class.getClassLoader();
        GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(loader.getResource(CREDENTIALS_FILE_PATH).getFile()))
                .createScoped(SCOPES);

        return credential;
    }

 

4.main method

서비스를 수행할 main method 이다.

spreadSheetId는 이전에 복사해둔 url의 중간값이다.

range는 작성할 sheet의 범위를 지정했다. [sheet의쪽이름]![시작]:[종료]

test data를 생성 후 Sheets 객체를 생성하고 update 메서드를 수행하였다.

 

public static void main(String[] args) throws IOException, GeneralSecurityException {
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();

    String spreadSheetId = "10V2jgduNh-DQ1FZN8-4bMUasSsSy4YbnSB16etzqAzE";
    String range = "sheet1!A1:C4"; // Sheet1의 A1부터 C4까지

    List<List<Object>> values = Arrays.asList(
            Arrays.asList("Name", "Age", "Gender"),
            Arrays.asList("Alice", 25, "Female"),
            Arrays.asList("Bob", 30, "Male"),
            Arrays.asList("choi", 32, "fmale1111111111"));
    ValueRange data = new ValueRange().setValues(values);

    Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
            .setApplicationName(APPLICATION_NAME)
            .build();

    service.spreadsheets().values().update(spreadSheetId, range, data)
            .setValueInputOption("USER_ENTERED")
            .execute();
}

 


5.전체 코드

main method 수행 시 아래와 같이 데이터가 삽입되는 것을 확인할 수 있다.

업무에서는 db에서 data를 select해서 range를 계산하고 sheet에 맞게끔 data를 가공하는 작업이 포함되었지만 단순 data insert의 경우 위와 같이 간단하게 코드를 작성할 수 있었다.

 

최종으로 작성한 클래스 코드는 아래와 같다.

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
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.gson.GsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
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.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class GoogleSheetService {
    // google sheets
    private static final String APPLICATION_NAME = "google-sheet-project";
    private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
    private static final List<String> SCOPES = Collections.singletonList(SheetsScopes.SPREADSHEETS);
    private static final String CREDENTIALS_FILE_PATH = "googlesheet/google_spread_sheet_key.json";

    private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT)
            throws IOException {
        ClassLoader loader = GoogleSheetService.class.getClassLoader();
        GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(loader.getResource(CREDENTIALS_FILE_PATH).getFile()))
                .createScoped(SCOPES);

        return credential;
    }

    public static void main(String[] args) throws IOException, GeneralSecurityException {
            final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();

        String spreadSheetId = "1PrjniLIPwS-eHicw9oRMpZffkL38PQQmm7N1dc59fAI";
        String range = "sheet1!A1:C4"; // Sheet1의 A1부터 C3까지

        List<List<Object>> values = Arrays.asList(
                Arrays.asList("Name", "Age", "Gender"),
                Arrays.asList("Alice", 25, "Female"),
                Arrays.asList("Bob", 30, "Male"),
                Arrays.asList("choi", 32, "fmale1111111111"));
        ValueRange data = new ValueRange().setValues(values);

        Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
                .setApplicationName(APPLICATION_NAME)
                .build();

        service.spreadsheets().values().update(spreadSheetId, range, data)
                .setValueInputOption("USER_ENTERED")
                .execute();

    }
}

 


* 질문이나 문의사항, 피드백은 댓글로 남겨주세요.