오진이 블로그

구글스프레드시트 API 활용하기(예제 포함) 본문

Development/Python

구글스프레드시트 API 활용하기(예제 포함)

오늘도 진이 2021. 7. 20. 10:44

개요

안녕하세요. 오늘도 진이 빠진 채로 글을 적습니다.

오늘은 파이썬과 Google Drive(구글 드라이브) API를 활용해 Google Spreadsheet(구글 스프레드시트) 업무를 자동화하는 방법에 대해 알아보겠습니다.

준비물

편집기

Visual Studio Code

Library

Google Drive API

gspread

oauth2client

계정

Google

설치

  1. 파이썬을 설치합니다.
    pip install python​
  2. 파이썬 라이브러리(gspread) 설치합니다.
    pip install gspread​
  3. 파이썬 라이브러리(oauth2client) 설치합니다.
    pip install oauth2client​


  4. 구글 개발자 인증을 진행합니다.
  • Google Drive API를 설치합니다.

사용자 인증을 진행합니다. 서비스 계정을 만듭니다.

  • 권한을 설정 합니다. 프로젝트의 탐색자, 편집자, 소유자, 뷰어 권한 모두를 부여했습니다.

  • JSON 파일에서 client_email 부분을 메모합니다.

예제

스트레드시트(Spreadsheet) 생성 및 사용자 추가

  • 구글 드라이드(Google Drive)에 접속합니다. 좌측 상단에 새로 만들기를 눌러줍니다.

  • 구글 스프레드시트(Google Spreadsheet)를 생성합니다.

  • 예제에서는 이름을 test로 바꿔 생성했습니다. 테스트 값을 입력합니다.

  • 공유를 눌러 구글 개발자 콘솔에서 얻은 client_email 을 사용자에 추가합니다.

  • 문서의 URL 값을 복사해둡니다. 스크립트에서 문서에 접근할 때 필요합니다.

  • 파이썬(Python) 코드를 작성합니다. 전체 예제를 작성했으며, 아래에서 부분별로 확인하겠습니다.
    import gspread
    from oauth2client.service_account import ServiceAccountCredentials
    
    scope = [
    'https://spreadsheets.google.com/feeds',
    'https://www.googleapis.com/auth/drive',
    ]
    
    json_file_name = 'pelagic-pod-319905-d29447ab8641.json'
    
    credentials = ServiceAccountCredentials.from_json_keyfile_name(json_file_name, scope)
    gc = gspread.authorize(credentials)
    
    spreadsheet_url = 'https://docs.google.com/spreadsheets/d/1gdTyTPtDPWt0pVDqYKmq1VJq35S4N7ts0VN5mUd_F_c/edit#gid=0'
    
    # 스프레스시트 문서 가져오기 
    doc = gc.open_by_url(spreadsheet_url)
    
    # 시트 선택하기
    worksheet = doc.worksheet('test')
    
    # 특정 셀 데이터 가져오기
    cell_data = worksheet.acell('B1').value
    print(cell_data)
    
    # 행 데이터 가져오기
    row_data = worksheet.row_values(1)
    print(row_data)
    
    # 열 데이터 가져오기
    column_data = worksheet.col_values(1)
    print(column_data)
    
    # 특정 영역 선택하여 데이터 가져오기
    # 범위(셀 위치 리스트) 가져오기
    range_list = worksheet.range('A1:D2')
    print(range_list)
    # 범위에서 각 셀 값 가져오기
    for cell in range_list:
        print(cell.value)
    
    # 특정 셀에 값 쓰기
    worksheet.update_acell('B1', 'b1 updated')
    
    # 행으로 데이터 추가하기
    worksheet.append_row(['new1', 'new2', 'new3', 'new4'])
    
    worksheet.insert_row(['new1', 'new2', 'new3', 'new4'], 4)
    
    # 시트 크기 조정하기
    worksheet.resize(10,4)
    
    # 스프레드시트 생성하기
    gs = gc.create('새로운 테스트') 
    
    worksheet = gs.add_worksheet(title='시트1', rows='1', cols='1')
    
    # 스프레드시트 공유, 소유권 부여하기
    gs.share('hleecaster@gmail.com', perm_type='user', role='owner')​

데이터 가져오기

셀 데이터 가져오기

  • B1 셀 값 가져오는 부분입니다.
    cell_data = worksheet.acell('B1').value
    print(cell_data)​

행 데이터 가져오기

  • 1행 값 가져오는 부분입니다.
    row_data = worksheet.row_values(1)
    print(row_data)​

열 데이터 가져오기

  • 1열 값 가져오는 부분입니다.
    column_data = worksheet.col_values(1)
    print(column_data)​

영역 데이터 가져오기

  • A1:D2 영역을 가져오는 부분입니다.
    # 범위(셀 위치 리스트) 가져오기
    range_list = worksheet.range('A1:D2')
    print(range_list)
    # 범위에서 각 셀 값 가져오기
    for cell in range_list:
        print(cell.value)​

데이터 쓰기

셀에 값 쓰기

  • B1 셀 값을 b1 updated 로 업데이트 하는 부분입니다.
    worksheet.update_acell('B1', 'b1 updated')​

행에 데이터 추가하기

  • append 를 이용해 맨 아래 한 행 추가하는 부분입니다. 구글 스프레드 시트 경우 1001번째에 추가됩니다.

  • insert 를 이용해 특정 위치에 한 행 추가하는 부분입니다.

시트 크기 조정하기

  • 초기 26개 열과 1000개 행이 있습니다.
  • 조정하게 되면 값 또한 사라집니다.
  • resize 를 이용해 10행 4열로 조정합니다.
    worksheet.resize(10,4)​

스프레드시트(Spreadsheet) 생성/공유하기

스프레드시트(Spreadsheet) 생성하기

gs = gc.create('새로운 테스트')
worksheet = gs.add_worksheet(title='시트1', rows='1', cols='1')

스프레드시트(Spreadsheet) 공유, 소유권 부여하기

gs.share('이메일아이디', perm_type='user', role='owner')

 

이제 그만 충전하러 가보겠습니다. 감사합니다.

 

참고자료

http://hleecaster.com/python-google-drive-spreadsheet-api/

https://docs.gspread.org/en/latest/index.html

 

Comments