61

我想知道如果你能指點我一個使用python讀/寫/從一個谷歌文檔/電子表格的例子。如何使用Python訪問(讀取,寫入)Google表格電子表格?

我看過谷歌文檔API在這裏https://developers.google.com/google-apps/spreadsheets/但不知道如果我點擊正確的鏈接。另外一個例子會有很大的幫助。

我想要做的是查詢基於不同列的查詢電子表格,更像是一個SQL查詢,然後使用數據做一些下游解析並將其放入另一個電子表格或doc文檔中。

最佳, -Abhi

+3

http://code.google.com/p/gdata-python-client/ – 2012-03-13 20:51:46

回答

-2

我認爲你正在尋找在API文檔頁面的細胞爲基礎的供稿部分。然後,您可以在Python腳本中使用PUT/GET請求,使用commands.getstatusoutputsubprocess

51

看一看GitHub - gspread

我發現它是非常容易使用,因爲你可以通過

first_col = worksheet.col_values(1) 

和一整排的

second_row = worksheet.row_values(2) 

檢索整列可以或多或少地建立一些基本的選擇...其中... = ...很容易。

+4

注意:gspread似乎沒有刪除行,單元格或列的功能 - 它只能調整電子表格或透明單元格的大小。這使它對我的目的毫無用處。 – Moshe 2014-08-10 16:24:19

+0

我不相信它是gspread,這就是問題......這是API。較舊版本的API版本(v1-v3)未提供該功能。 [新的v4 API可以刪除](http://developers.google.com/sheets/samples/rowcolumn)。請參閱上面的[我的回答](http://stackoverflow.com/a/37868852/5049813)以獲取更多信息。 – wescpy 2016-12-06 00:34:32

+0

嘗試gspread api v4端口[pygsheets](https://github.com/nithinmurali/pygsheets) - 作者 – nithin 2017-03-24 16:07:01

28

我知道這個帖子現在已經很老了,但這裏有一些關於Google Docs API的體面文檔。這是很難找到,但很有用,所以也許它會幫助你一些。 http://pythonhosted.org/gdata/docs/api.html

我最近使用gspread作爲項目來繪製員工時間數據。我不知道它可以幫助你多少,但是這裏有一個鏈接到代碼:https://github.com/lightcastle/employee-timecards

Gspread讓我覺得很容易。我也能夠添加邏輯來檢查各種條件,以創建月初至今的結果。但我只是導入了整個dang電子表格並從那裏解析它,所以我不能100%確定它正是你正在尋找的東西。祝你好運。

+0

第二個鏈接現在重定向到第一個 – Kariamoss 2016-05-04 10:50:53

+0

此答案現在已過時。請參閱[wescpy的答案](http://stackoverflow.com/a/37868852/5049813)。 – 2016-09-17 16:57:16

79

(君2016年12月)這裏大部分的答案現在是外的日期爲:1)GData APIs是上一代谷歌的API,這就是爲什麼它是很難@Josh Brown地發現,老的GData文檔API文檔。雖然並非所有的GData API已被棄用,all newer Google APIs使用the Google Data protocol;和2)Google released a new Google Sheets API(不是GData)。爲了使用新的API,您需要獲得the Google APIs Client Library for Python(與pip install -U google-api-python-client [或Python 3的pip3]一樣簡單),並使用最新的Sheets API v4+,這比舊的API版本靈活得多。

這裏有一個code sample來自官方文檔,以幫助你開始起步。但是,這裏有稍長,使用可以從(視頻加博客文章)學習API的更多的「真實世界」的例子:

最新表API提供了舊版本無法使用,也就是讓開發人員的編程訪問功能(如創建凍結行,執行單元格格式化,調整行/列大小,添加數據透視表,創建圖表等等),但不能將其視爲您可以執行搜索的某個數據庫並從中獲取選定的行。你基本上必須在這個API的基礎上構建一個查詢層。一種替代方法是使用the Google Charts Visualization API query language,它確實支持SQL-like querying。你自己也可以query from within the Sheet。請注意,此功能在v4 API之前就已存在,並且該security model was updated in Aug 2016。要了解更多信息,請從Google Developer Expert檢查my G+ reshare to a full write-up

還要注意,表API是主要用於編程方式訪問電子表格操作&的功能如上所述,但執行文件 - 電平訪問這樣進口/出口,複製,移動,重命名等,使用改爲Google Drive API

(*) - TL; DR:上傳純文本文件到驅動器,導入/轉換到谷歌文檔格式,則該文件導出爲PDF。以上帖子使用Drive API v2; this follow-up post描述了將其遷移到Drive API v3,這裏是一個developer video結合「窮人的轉換器」的帖子。

要詳細瞭解如何在Python中使用Google API,請查看my blog以及我製作的各種Google開發人員視頻(series 1series 2)。

ps。至於谷歌文檔去,目前沒有可用的REST API,所以以編程方式訪問文檔的唯一方法是使用Google Apps Script(其中像Node.js是瀏覽器以外的JavaScript,而不是運行在Node服務器上,這些應用程序運行在Google的雲中;也可以查看我的intro video。)使用Apps腳本,您可以構建一個Docs appadd-on for Docs(以及其他諸如表格&表單)。

+5

感謝wescpy,這需要被提起。 – 2016-06-20 19:59:01

6

最新的google api文檔文檔如何使用python寫入電子表格,但有點難以導航。這裏是一個鏈接to an example of how to append

以下代碼是我第一次成功嘗試附加到谷歌電子表格。

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() 
+0

問題的唯一具體答案。 – e4c5 2017-02-24 13:21:09

5

看看gspread端口API V4 - pygsheets。它應該是非常容易使用,而不是谷歌客戶端。

樣品例如

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("[email protected]") 

查看該文檔here

作者在這裏。

+0

'pygsheets'是'gspread'的一個端口還是完整的重寫? – Xocoatzin 2017-08-26 19:23:09

+0

它的全部重寫雖然API保持幾乎相似 – nithin 2017-08-26 20:50:24

+0

很高興我滾動下來。對我來說,這是迄今爲止最簡單的解決方案。有關如何創建憑據以授權使用Google表格的一些信息會很有用,如https://www.themarketingtechnologist.co/google-oauth-2-enable-your-application-to-access-data-from-谷歌用戶/ – Katu 2017-11-18 19:41:00

相關問題