Notice
Recent Posts
Recent Comments
Link
«   2025/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
Tags
more
Archives
Today
Total
관리 메뉴

KJH

google spread sheet API 본문

Python

google spread sheet API

모이스쳐라이징 2021. 3. 30. 00:35

1. GCP api 계정 생성 및 sheet 등록

1.1 GCP 콘솔 주소

1.2 GCP 콘솔 접속

1.3 검색창에 google sheets api 검색

1.4 api 활성화

1.5 서비스계정 생성

 

1.6 이름 입력 후 [가입 완료 및 계속] 클릭

1.7 권한 설정

1.8 완료 버튼 클릭

 

1.9 키관리 클릭

1.10 새키 만들기

1.11 JSON 타입으로 생성 후 다운로드

1.12 키 형태

1.13 키 내용중 client_email 복사 후 공유 계정으로 등록

1.14 키 적용

  • 새로 생성한 키는 적용하려고 하는 사업에 각각 등록 해야함

 

2. 사용법 

 

2.1 linux에서 python 사용 및 모듈 설

sudo yum install -y python3
sudo yum install -y epel-release

sudo pip3 install --upgrade google-api-python-client oauth2client
sudo pip3 install gspread

 

 

2.2 spread api 사용

import re
import sys
from datetime import datetime

import gspread
import pygsheets
from gspread.models import Cell, Spreadsheet
from oauth2client.service_account import ServiceAccountCredentials

##### global
now = datetime.now()
formattedDate = "XXXX" + now.strftime("%Y-%m")
json_file="XXXX"
json_flle_path="XXXX"
frame="XXXX"
spread_sheet_name="XXXX"
#####
with open("XXXX", "r") as f:
    list_file = f.read().split()
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name(json_flle_path, scope)
gc = gspread.authorize(credentials)
spreadsheet_url = 'https://docs.google.com/spreadsheets/d/XXXXXX/edit#gid=985477863'
######

def main():
    check_worksheet_name()

def check_worksheet_name():
    doc = gc.open_by_url(spreadsheet_url)
    try:
        worksheet = doc.worksheet(formattedDate)
    except:
        worksheet = None
        pass
    
    if worksheet == None:
        create_worksheet()
    post_data()

def create_worksheet():
    gc = pygsheets.authorize(service_account_file=json_file)
    doc = gc.open(spread_sheet_name)
    post_create_worksheet = doc.add_worksheet(formattedDate, src_worksheet=doc.worksheet_by_title(frame))
    
def post_data():
    doc = gc.open_by_url(spreadsheet_url)
    worksheet = doc.worksheet(formattedDate)
    worksheet.append_row(list_file, value_input_option='USER_ENTERED')

if __name__ == '__main__':
    main()

 

2.3 shell script에서 python 구동 방법

export PATH=/usr/local/bin/python3:$PATH

python3 /app/status/spread.py

 

 

 

'Python' 카테고리의 다른 글

Slack API (fastapi - slack_bolt)  (0) 2024.07.19
azure openAI (GPT4.0, ada-002)  (0) 2023.11.26
Slack API (Legacy)  (0) 2023.10.20
비동기 ??? asyncio ???  (0) 2022.05.15
Youtube Playlist Auto Download  (0) 2021.01.01