Python으로 Google 스프레드 시트에 액세스 (읽기, 쓰기)하려면 어떻게하나요?
파이썬을 사용하여 Google 문서 / 스프레드 시트에서 읽기 / 쓰기의 예를 알려줄 수 있는지 궁금합니다.
https://developers.google.com/google-apps/spreadsheets/ 여기에서 google docs API를 보았지만 올바른 링크를 클릭했는지 확실하지 않습니다. 또한 한 가지 예가 큰 도움이 될 것입니다.
내가하려는 것은 SQL 쿼리와 같은 다른 열을 기반으로 스프레드 시트를 쿼리 한 다음 데이터를 사용하여 다운 스트림 구문 분석을 수행하고 Google 문서의 다른 스프레드 시트 또는 문서에 넣는 것입니다.
최고, -Abhi
(2016 년 6 월 -12 월) 여기에있는 대부분의 답변은 다음과 같이 구식입니다. 1) GData API 는 이전 세대의 Google API이며, 이것이 @ Josh Brown 이 이전 GData Docs API 문서를 찾기 가 어려웠던 이유 입니다. 모든 GData API가 더 이상 사용되지 는 않지만 모든 최신 Google API 는 Google 데이터 프로토콜을 사용 하지 않습니다 . 2) Google 은 새로운 Google Sheets API (GData가 아님)를 출시했습니다 . 새 API를 사용하려면 Python 용 Google API 클라이언트 라이브러리 ( [또는 Python 3] 만큼 쉽습니다 )를 다운로드하고 최신 Sheets API v4 이상을 사용해야합니다.pip install -U google-api-python-client
pip3
, 이는 이전 API 릴리스보다 훨씬 강력하고 유연합니다.
다음 은 시작하는 데 도움이되는 공식 문서의 코드 샘플 입니다. 그러나 여기에서 배울 수있는 API 사용에 대한 약간 더 긴 "실제"예제가 있습니다 (동영상 및 블로그 게시물).
- SQL 데이터를 Sheet 및 코드 심층 분석 게시물로 마이그레이션
- Sheets API 및 코드 심층 분석 게시물을 사용하여 텍스트 서식 지정
- 스프레드 시트 데이터 와 코드 심층 분석 게시물 에서 슬라이드 생성
최신 Sheets API는 이전 버전에서 사용할 수 없었던 기능을 제공합니다. 즉, 개발자가 사용자 인터페이스를 사용하는 것처럼 시트에 프로그래밍 방식으로 액세스 할 수 있습니다 (고정 된 행 생성, 셀 서식 수행, 행 / 열 크기 조정, 피벗 테이블 추가, 차트 생성 등). .), 검색을 수행하고 선택한 행을 가져올 수있는 데이터베이스 인 것처럼 보이지는 않습니다. 기본적으로이를 수행하는 API 위에 쿼리 계층을 구축해야합니다. 한 가지 대안은 SQL과 유사한 쿼리를 지원 하는 Google Charts Visualization API 쿼리 언어 를 사용 하는 것 입니다. 시트 자체 에서 쿼리 할 수도 있습니다 . 이 기능은 v4 API 이전에 존재했으며 보안 모델이 2016 년 8 월 에 업데이트되었습니다.. 더 많은 내용 확인 전체 쓰기까지 내 G +의 다시 공유를 A로부터 구글 개발자 전문가 .
또한 Sheets API는 주로 위에서 설명한 스프레드 시트 작업 및 기능에 프로그래밍 방식으로 액세스하기위한 것이지만 가져 오기 / 내보내기, 복사, 이동, 이름 바꾸기 등과 같은 파일 수준 액세스 를 수행 하려면 대신 Google Drive API를 사용하세요. Drive API 사용의 예 :
- Google 드라이브에 파일 나열 및 심층 분석 게시물 코딩
- Google 드라이브 : 파일 업로드 및 다운로드 및 "가난한 사람의 일반 텍스트를 PDF로 변환"코드 심층 분석 게시물 (*)
- Google 시트를 CSV 블로그 게시물 로만 내보내기
(*)-TL; DR : 일반 텍스트 파일을 드라이브에 업로드하고 Google 문서 형식으로 가져 오기 / 변환 한 다음 해당 문서를 PDF로 내 보냅니다. 위의 게시물은 Drive API v2를 사용합니다. 이 후속 게시물 에서는 드라이브 API v3로 마이그레이션하는 방법에 대해 설명하고 여기에 "가난한 사람의 변환기"게시물을 결합한 개발자 동영상이 있습니다.
일반적으로 Python과 함께 Google API를 사용하는 방법에 대해 자세히 알아 보려면 제 블로그 와 제가 제작 중인 다양한 Google 개발자 동영상 ( 시리즈 1 및 시리즈 2 )을 확인하세요.
추신. 지금까지로 Google 문서 도구가 간다,이 시간에 사용할 수있는 REST API는 유일한 방법은 프로그래밍 방식으로 문서에 액세스 할 수 있도록 사용하는 것입니다,이없는 Google 애플리케이션 스크립트 대신의, Node.js를 같이 브라우저의 자바 스크립트 밖에 ( Node 서버에서 실행되는 이러한 앱은 Google의 클라우드에서 실행되며 내 소개 동영상 도 확인하세요 .) Apps Script를 사용하여 문서 앱 또는 문서 용 부가 기능 (및 스프레드 시트 및 설문지와 같은 기타 기능)을 빌드 할 수 있습니다 .
2018 년 7 월 업데이트 : 위의 "ps." 더 이상 사실이 아닙니다. G Suite 개발자 팀은 Google Cloud NEXT '18에서 새로운 Google 문서 REST API를 사전 발표했습니다. 새 API의 조기 액세스 프로그램에 관심이있는 개발자는 https://developers.google.com/docs 에서 등록해야합니다 .
2019 년 2 월 업데이트 : 지난 7 월 미리보기 위해 출시 된 Docs API는 이제 모든 사용자가 일반적으로 사용할 수 있습니다 . 자세한 내용 은 출시 게시물 을 읽어 보세요.
GitHub-gspread를 살펴보십시오 .
사용하기가 매우 쉽고 다음을 통해 전체 열을 검색 할 수 있기 때문에
first_col = worksheet.col_values(1)
그리고 전체 행
second_row = worksheet.row_values(2)
당신은 어느 정도 기본 선택 ...
을 ... = ...
쉽게 할 수 있습니다.
이 스레드가 이제 오래되었다는 것을 알고 있지만 여기에 Google Docs API에 대한 괜찮은 문서가 있습니다. 찾기가 엄청나게 어려웠지만 유용했기 때문에 아마도 도움이 될 것입니다. http://pythonhosted.org/gdata/docs/api.html .
최근에 직원 시간 데이터를 그래프로 표시하는 프로젝트에 gspread를 사용했습니다. 얼마나 도움이 될지 모르겠지만 여기에 코드 링크가 있습니다 : https://github.com/lightcastle/employee-timecards
Gspread는 나를 위해 일을 매우 쉽게 만들었습니다. 또한 다양한 조건을 확인하는 로직을 추가하여 월간 및 연간 누계 결과를 생성 할 수있었습니다. 하지만 방금 전체 dang 스프레드 시트를 가져 와서 거기에서 파싱했기 때문에 정확히 원하는 내용인지 100 % 확신 할 수 없습니다. 행운을 빌어 요.
api v4- pygsheets 용 gspread 포트를 살펴보십시오 . Google 클라이언트보다 사용하기가 매우 쉽습니다.
샘플 예
import pygsheets
gc = pygsheets.authorize()
# Open spreadsheet and then workseet
sh = gc.open('my new ssheet')
wks = sh.sheet1
# Update a cell with value (just to let him know values is updated ;) )
wks.update_cell('A1', "Hey yank this numpy array")
# update the sheet with array
wks.update_cells('A2', my_nparray.to_list())
# share the sheet with your friend
sh.share("myFriend@gmail.com")
여기에서 작성하십시오.
최신 Google API 문서는 Python으로 스프레드 시트에 쓰는 방법을 문서화하지만 탐색하기가 조금 어렵습니다. 다음은 을 추가하는 방법의 예에 대한 링크 입니다.
다음 코드는 Google 스프레드 시트에 추가하는 첫 번째 성공적인 시도입니다.
import httplib2
import os
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
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'
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,
'mail_to_g_app.json')
store = oauth2client.file.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 add_todo():
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 = 'PUT YOUR SPREADSHEET ID HERE'
rangeName = 'A1:A'
# https://developers.google.com/sheets/guides/values#appending_values
values = {'values':[['Hello Saturn',],]}
result = service.spreadsheets().values().append(
spreadsheetId=spreadsheetId, range=rangeName,
valueInputOption='RAW',
body=values).execute()
if __name__ == '__main__':
add_todo()
Sheetfu를 살펴볼 수 있습니다 . 다음은 README의 예입니다. 마치 데이터베이스 테이블 인 것처럼 스프레드 시트와 상호 작용할 수있는 매우 쉬운 구문을 제공합니다.
from sheetfu import Table
spreadsheet = SpreadsheetApp('path/to/secret.json').open_by_id('<insert spreadsheet id here>')
data_range = spreadsheet.get_sheet_by_name('people').get_data_range()
table = Table(data_range, backgrounds=True)
for item in table:
if item.get_field_value('name') == 'foo':
item.set_field_value('surname', 'bar') # this set the surname field value
age = item.get_field_value('age')
item.set_field_value('age', age + 1)
item.set_field_background('age', '#ff0000') # this set the field 'age' to red color
# Every set functions are batched for speed performance.
# To send the batch update of every set requests you made,
# you need to commit the table object as follow.
table.commit()
면책 조항 : 저는이 도서관의 저자입니다.
This thread seems to be quite old. If anyone's still looking, the steps mentioned here : https://github.com/burnash/gspread work very well.
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import os
os.chdir(r'your_path')
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
gc = gspread.authorize(creds)
wks = gc.open("Trial_Sheet").sheet1
wks.update_acell('H3', "I'm here!")
Make sure to drop your credentials json file in your current directory. Rename it as client_secret.json.
You might run into errors if you don't enable Google Sheet API with your current credentials.
I think you're looking at the cell-based feeds section in that API doc page. Then you can just use the PUT/ GET requests within your Python script, using either commands.getstatusoutput
or subprocess
.
'Program Tip' 카테고리의 다른 글
Ruby on Rails에서 쿼리 문자열 인 것처럼 문자열 구문 분석 (0) | 2020.11.06 |
---|---|
파이썬에서 문자열을 제목 대소 문자로 변환하는 방법은 무엇입니까? (0) | 2020.11.06 |
li의 두 번째 줄은 CSS 재설정 후 글 머리 기호 아래에서 시작합니다. (0) | 2020.11.06 |
--resource-rules는 mac os x> = 10.10에서 더 이상 사용되지 않습니다. (0) | 2020.11.06 |
테스트 조치에 대해 구성표가 구성되지 않았습니다 (iOS xcode 프로젝트). (0) | 2020.11.06 |