본문 바로가기
Developer/Python

Python에서 Google Sheets 를 API를 통해 사용하는 방법

by 김씩씩 2021. 11. 15.

Python에서 Google Sheets 를 API를 통해 사용하는 방법

 

Python에서 Google Sheets 를 API를 통해 사용하는 방법을 알려드리도록 하겠습니다.

 

1. Google Coloud Platform API Setting

1-1. Google Cloud Platform Prject 생성

먼저 Google Cloud Platform Project를 생성하셔야합니다.

Google Cloud PlatformProject를 이미 가지고 계신분이 아니라면 Project를 먼저 하나 생성해주세요.

※ 이미 Project를 가지고 있고, 해당 Project로 사용하실 분들이라면 이미 존재하는 Project에서 진행하시면 되겠습니다.

 

1-2. Google Drive API Enable

Google Cloud Platform에서 Google Drive API를 검색하여 선택합니다.

 

Google Drive APIENABLE(사용) 버튼을 클릭하여 사용하도록 합니다.

 

1-3. Google Sheets API Enable

Google Cloud Platform에서 Google Sheets API를 검색합니다.

 

Google Sheets APIENABLE(사용) 버튼을 클릭하여 사용하도록 합니다.

 

1-4. Service Account 생성

Google API 를 사용할 때 사용할 Service Account가 필요합니다.

Google Cloud Platform 메뉴에서 [IAM & Admin] 에서 [Service Accounts] 로 들어갑니다.

 

[CREATE SERVICE ACCOUNT] 버튼을 클릭하여 서비스 계정을 만들도록 하겠습니다.

※ 이미 Service Account를 가지고 계신 분은 해당 계정 키를 사용하셔도 상관없습니다.

 

Service Account의 이름을 입력하고 다음으로 넘어갑니다.

 

Service Account의 권한을 선택합니다.

생성할 서비스 계정의 권한을 아주 세부적으로 지정할수도 있지만,

현재 이 글에서는 그런 것 까지 다루기엔 글이 너무 길어지니 다음에 기회가 있으면 설명드리도록 하겠습니다.

간단히 Basic > Editor 혹은 Owner를 선택해주시면 Google Sheets 를 사용하는데 문제가 없습니다.

 

생성할 Service Account에 액세스 할 수 있는 권한을 부여할 계정을 입력하는 부분인데,

현재로서는 필요없는 부분이니 건너뛰도록 하겠습니다.

[DONE] 버튼을 클릭하여 Service Account 생성을 완료합니다.

 

Service Account 가 생성되었으면 우측에 [Actions] 버튼을 클릭하고 [Manage Keys]를 클릭합니다.

 

[ADD Key] > [Create new key] 버튼을 클릭하여 새로운 키를 생성을 시작합니다.

 

Key type 으로 [JSON] 을 선택하고 [CREATE] 버튼을 클릭하여 키를 생성합니다.

 

json 파일 형식의 키가 생성되면서 다운로드가 됩니다.

이제 생성된 키를 사용하시면 되겠습니다.

 

2. Google Sheet 사용 권한 부여

생성한 Sevice Account에게 사용할 Google Sheet에 대하여 사용 권한을 부여해줘야 합니다.

사용할 Google Sheet 에 들어가서 우측 상단에 [Share] 버튼을 클릭합니다.

 

이전에 생성한 Service Account의 Email에 Python으로 다룰 Google Sheet를 공유합니다.

Editor 권한을 주어서 데이터를 보고 수정도 할 수 있게 해줍니다.

 

3. Python 에서 Google Sheet 사용

이제 사전준비는 모두 끝났고 Python에서 Google Sheet를 사용하시면 되겠습니다.

 

3-1. 사용할 패키지 설치

우선 사용할 패키지를 설치합니다.

pip install oauth2client
pip install gspread

위 명령어를 통해 oauth2clientgspread 패키지를 설치합니다.

 

3-2. API 사용을 위한 인증

from oauth2client.service_account import ServiceAccountCredentials
import gspread

scope = [
    "https://spreadsheets.google.com/feeds",
    "https://www.googleapis.com/auth/drive",
]

json_key_path = "./test.json"	# JSON Key File Path

credential = ServiceAccountCredentials.from_json_keyfile_name(json_key_path, scope)
gc = gspread.authorize(credential)

 

위 코드를 통해 API 사용을 위한 인증과정을 거칩니다.

이전에 다운로드한 Json Key 파일을 사용하여 인증과정을 거치시면 되겠습니다.

 

혹은,

oauth2client 를 사용하지 않고 인증받을 수 있는 방법도 있습니다.

import gspread

json_key_path = "./test.json" # JSON Key File Path

gc = gspread.service_account(filename=json_key_path)

gspread의 service_account() 를 사용하여 인증과정을 거칠 수도 있습니다.

 

편한 방법을 사용하시면 되겠습니다.

 

3-3. Spread Sheet 열기

from oauth2client.service_account import ServiceAccountCredentials
import gspread

scope = [
    "https://spreadsheets.google.com/feeds",
    "https://www.googleapis.com/auth/drive",
]

json_key_path = "./test.json" # JSON Key File Path

credential = ServiceAccountCredentials.from_json_keyfile_name(json_key_path, scope)
gc = gspread.authorize(credential)


# URL로 열기
spreadsheet_url = "https://docs.google.com/spreadsheets/d/18n328MQoyReTNKuvvs_3YgLO-JW-bGWodQcKZen63LA/edit#gid=0"
doc = gc.open_by_url(spreadsheet_url)

# OR

# Spread Sheet Key로 열기
spreadsheet_key = "18n328MQoyReTNKuvvs_3YgLO-JW-bGWodQcKZen63LA"
doc = gc.open_by_key(spreadsheet_key)

# OR

# Spread Sheet 이름으로 열기
doc = gc.open("test")

스프레드 시트를 여는 방법에는 3가지가 있습니다.

  • open_by_url() 함수를 사용하여 사용하려는 스프레드 시트의 URL로 열 수 있습니다.
  • open_by_key() 함수를 사용하여 사용하려는 스프레드 시트의 URL에 포함되어있는 Key를 사용하여 열 수 있습니다.
  • open() 함수를 사용하여 사용하려는 스프레드 시트의 이름으로 열 수 있습니다.

 

3-4. Sheet 선택

from oauth2client.service_account import ServiceAccountCredentials
import gspread

scope = [
    "https://spreadsheets.google.com/feeds",
    "https://www.googleapis.com/auth/drive",
]

json_key_path = "./test.json" # JSON Key File Path

credential = ServiceAccountCredentials.from_json_keyfile_name(json_key_path, scope)
gc = gspread.authorize(credential)

spreadsheet_key = "18n328MQoyReTNKuvvs_3YgLO-JW-bGWodQcKZen63LA"
doc = gc.open_by_key(spreadsheet_key)

# Sheet 선택
sheet = doc.worksheet("Sheet1")

worksheet("Sheet 이름")을 사용하여 Sheet를 선택할 수 있습니다.

 

3-5. Sheet 다루기

이제 선택한 Sheet의 값을 찾고, 가져오고, 업데이트하고, 삭제하는 등 원하는 것들을 하시면 됩니다.

그 중에서 값을 가지고 오는 방법에 대해서만 몇가지 알려드리도록 하겠습니다.

from oauth2client.service_account import ServiceAccountCredentials
import gspread

scope = [
    "https://spreadsheets.google.com/feeds",
    "https://www.googleapis.com/auth/drive",
]

json_key_path = "./test.json" # JSON Key File Path

credential = ServiceAccountCredentials.from_json_keyfile_name(json_key_path, scope)
gc = gspread.authorize(credential)

spreadsheet_key = "18n328MQoyReTNKuvvs_3YgLO-JW-bGWodQcKZen63LA"
doc = gc.open_by_key(spreadsheet_key)

sheet = doc.worksheet("Sheet1")


# 모든 값을 list로 가져오기
list_of_lists = sheet.get_all_values()
print(list_of_lists)

# 모든 값을 dict로 가져오기
list_of_dicts = sheet.get_all_records()
pprint(list_of_dicts)

# Cell 값 가져오기
value_a1 = sheet.get('A1')
print(value_a1)

# Output
# [['물품', '재고', '가격'], ['사과', '1230', '1000'], ['바나나', '1580', '2000'], ['수박', '985', '10000'], ['참외', '863', '500']]
#
# [{'물품': '사과', '재고': 1230, '가격': 1000}, {'물품': '바나나', '재고': 1580, '가격': 2000}, {'물품': '수박', '재고': 985, '가격': 10000}, {'물품': '참외', '재고': 863, '가격': 500}]
#
# [['물품']]

get_all_values(), get_all_records(), get() 을 사용해 시트의 값을 가지고오는 예시를 보여드렸는데요.

이 밖에도 값을 가져오는 방법, 셀 찾는 방법, 업데이트 방법, 삭제 등등 많은 기능이 gspread에 있으니 찾아보시고 사용하시면 되겠습니다.

아래 참고자료에 남겨두었으니 확인해보시면 되겠습니다.

 

이상으로 Python에서 Google Sheets 를 API를 통해 사용하는 방법에대한 설명을 마치도록 하겠습니다.

 

 

도움이 되셨다면 공감, 댓글 부탁드립니다!

궁금하신 점이나 요청사항은 언제든지 말씀해주세요!

피드백도 언제나 환영입니다!

 

감사합니다.

 

 

참고자료 : https://docs.gspread.org/en/latest/index.html


댓글