본문으로 건너뛰기
yceffort
PostsSeriesTagsAbout🧪 Research
EN

Tweaks

theme
accent palette
film grain
minimal mode
BACK TO INDEX
◆ ESSAY
--min
--year
KOoriginal

mailMail icongithubtwitter
yceffort
•
© 2026
•
https://yceffort.kr
BACK TO INDEX
◆ ESSAY

업무 자동화 (1) - 구글 스프레드 시트 API 활용하기

avatar
yceffort
2019-02-14 · 3분
3min
2019year
KOoriginal
pythonautomation

구글 스프레드 시트를 파이썬에서 조작해보자. 내가 할일은 1. 스프레드시트를 읽고 2. 스프레드시트에 쓰는 두가지 작업이다.

import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

SCOPES = ['https://www.googleapis.com/auth/spreadsheets']

class GoogleSheetInit():

    def __init__(self):
        self.creds = None

    def initialize(self):
        creds = None

        if os.path.exists('token.pickle'):
            with open('token.pickle', 'rb') as token:
                creds = pickle.load(token)
        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file('../credentials.json', SCOPES)
                creds = flow.run_local_server()
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)

        self.creds = creds

구글 docs에 접근하는 방법은 두가지인데, 한가지는 oauth2기반 인증과, 다른 한가지는 api_key방식 인증이다. api_key 인증 방식은 요청시에 parameter로 api key를 보내는 방식인데, 안타깝게도 보안상의 문제로 인해 전체 공개된 문서에만 접근할 수 있다.

따라서 제한적으로 공개되어 있는 문서에 접근하기 위해서는 oauth2 방식을 활용해야 한다.

google_sheet = GoogleSheetInit()
google_sheet.initialize()

실행하게 되면 브라우저에서 구글 계정 인증을 받게 된다. 계정인증을 거친 뒤에는 인증 정보가 token.pickle에 남아서 이 후부터는 별도의 인증없이 접근할 수 있다. 그리고 해당 인증정보를 파이썬 코드에서 사용할 수 있도록 creds가 반환된다.

자세한 api 스펙은 여기에서 참조하면 된다.

스프레드시트 읽기

service = build('sheets', 'v4', credentials=self.creds)
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=self.sheet_id, range=self.sheet_range).execute()
values = result.get('values', )

sheet_id는 해당 스프레드 시트의 id인데, url에 나와있다. 그리고 sheet_range는 시트이름!A1:Z1 이런식으로 접근하면 된다.

enumerate(values)

으로 접근할 수 있다.

스프레드시트 쓰기

request = sheet.values().update(spreadsheetId=self.sheet_id, range=range, valueInputOption='RAW', body={ "values": [[value]]})
response = request.execute()

body영역은 실제 스프레드시트에 쓰려고 하는 영역의 크기만큼 설정하면 된다. 위의 예제에서는 단순히 셀 1개에만 쓰는 케이스다.

관련 글

  • #python#backend

    [Python] Send ncloud sms message

    네이버 클라우드 플랫폼의 서비스 중 하나인 https://www.ncloud.com/product/applicationService/sens 로 SMS를 발송하는 예제. ncloud서비스를 다 써본건 아니지만, `make_signature`는 전 서비스에 다 똑같이 쓸 수 있을 것 같은 기분이다. ```python import time import req...

    2020-03-17·1분
  • #computer-vision#python

    Computer Vision 01) - Image Representation

    ## Image Representation & Classification ### Images as Grids of Pixels ```python import numpy as np from skimage import io import matplotlib.image as mpimg import matplotlib.pyplot as plt import cv...

    2019-04-01·2분
  • #web-scraping#python

    초보를 위한 웹크롤링: 네이버 영화 댓글 크롤링하기

    e 파이썬과 파이썬 라이브러리 (beatifulSoup)를 활용하여 네이버 영화 댓글 크롤링 해보기 ## 1. 크롤링하려는 웹페이지의 구조를 살펴보기 인크레더블 평점 댓글 페이지를 먼저 살펴보겠습니다. [여기](https://movie.naver.com/movie/bi/mi/point.nhn?code=136990&onlyActualPointYn=Y#po...

    2018-11-06·14분

새 글을 놓치고 싶지 않으시다면 RSS로 구독해 주세요.

RSS 구독 →

yceffort — 프론트엔드 엔지니어입니다. 발표·기술 자문·기고 문의는 이곳에서 받고 있습니다.

← Back to the blogIssue on GitHub →