티스토리 뷰

원문은 : https://developers.google.com/sheets/quickstart/python?hl=ko 여기

준비물은

  • 파이썬 2.6이상
  • pip 패키지 관리자(대부분 파이썬 설치할때 딸려온다)
  • 인터넷 접근 가능 환경과 인터넷 브라우저.
  • 구글 계정.


Step 1: 구글 스프레드 시트 API켜기

  1. 우선 https://console.developers.google.com/flows/enableapi?apiid=sheets.googleapis.com&hl=ko 에 접속하여 프로젝트를 선택하거나 생성합니다. 그러면 자동적으로 API가 켜집니다. 계속을 누르고사용자 인증 정보로 이동합니다.
  2. 사용자 인증정보 추가 페이지에서, 취소 버튼을 누릅니다.
  3. 페이지의 윗 부분에서 OAuth 동의 화면 consent screen 탭을 선택합니다. 이메일 주소를 선택하고,  사용자에게 표시되는 제품 이름을 입력합니다. 만약 이미 설정되어있지 않았다면, 아래의 저장 버튼을 눌러줍시다.
  4. 사용자 인증 정보 탭을 누르고, 사용자 인증 정보 만들기 버튼을 누른 다음 , OAuth 클라이언트 ID 버튼을 선택합니다.
  5. 애플리케이션 유형에서 기타를선택하고, 이름 "Google Sheets API Quickstart" 라고 입력합니다. 그 다음 생성 버튼을 클릴합니다.
  6. 결과창을 보기위해 확인 버튼을 클릭합니다.
  7. 클라이언트 ID 버튼 오른쪽에 있는  (Download JSON) 버튼을 클릭하여 줍니다..
  8. 이 파일을 작업폴더로 옮기고 파일이름을 client_secret.json으로 바꾸어 줍니다.

Step 2: 구글 클라이언트 라이브러리 설치하기

$ pip install --upgrade google-api-python-client

명령어로 설치. 파이썬 2.7이나 3.4이상만 지원, 자세한건 installation참고


Step 3: 샘플 실행해보기

quickstart.py라는 파일을 만들어 줍니다.


from __future__ import print_function
import httplib2
import os

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

try:
   
import argparse
    flags
= argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags
= None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json
SCOPES
= 'https://www.googleapis.com/auth/spreadsheets.readonly'
CLIENT_SECRET_FILE
= 'client_secret.json'
APPLICATION_NAME
= 'Google Sheets API Python Quickstart'


def get_credentials():
   
"""Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """

    home_dir
= os.path.expanduser('~')
    credential_dir
= os.path.join(home_dir, '.credentials')
   
if not os.path.exists(credential_dir):
        os
.makedirs(credential_dir)
    credential_path
= os.path.join(credential_dir,
                                   
'sheets.googleapis.com-python-quickstart.json')

    store
= Storage(credential_path)
    credentials
= store.get()
   
if not credentials or credentials.invalid:
        flow
= client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow
.user_agent = APPLICATION_NAME
       
if flags:
            credentials
= tools.run_flow(flow, store, flags)
       
else: # Needed only for compatibility with Python 2.6
            credentials
= tools.run(flow, store)
       
print('Storing credentials to ' + credential_path)
   
return credentials

def main():
   
"""Shows basic usage of the Sheets API.

    Creates a Sheets API service object and prints the names and majors of
    students in a sample spreadsheet:
    https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
    """

    credentials
= get_credentials()
    http
= credentials.authorize(httplib2.Http())
    discoveryUrl
= ('https://sheets.googleapis.com/$discovery/rest?'
                   
'version=v4')
    service
= discovery.build('sheets', 'v4', http=http,
                              discoveryServiceUrl
=discoveryUrl)

    spreadsheetId
= '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
    rangeName
= 'Class Data!A2:E'
    result
= service.spreadsheets().values().get(
        spreadsheetId
=spreadsheetId, range=rangeName).execute()
    values
= result.get('values', [])

   
if not values:
       
print('No data found.')
   
else:
       
print('Name, Major:')
       
for row in values:
           
# Print columns A and E, which correspond to indices 0 and 4.
           
print('%s, %s' % (row[0], row[4]))


if __name__ == '__main__':
    main
()

위 코드 입력후 실행!


코드의 의미나 사용법에 대해서는는 https://developers.google.com/sheets/guides/concepts?hl=ko 참고

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함