2016-04-09 5 views
8

मैं Google स्प्रेडशीट कार्यपुस्तिका के भीतर प्रत्येक वर्कशीट के लिए URL के भीतर वर्कशीट आईडी प्राप्त करने के लिए एक विधि की पहचान करना चाहता हूं। उदाहरण के लिए, 'Sheet2' this workbook के लिए कार्यपत्रक आईडी '+१२४४३६९२८०', है, क्योंकि यह यूआरएल https://docs.google.com/spreadsheets/d/1yd8qTYjRns4_OT8PbsZzH0zajvzguKS79dq6j--hnTs/edit#gid=1244369280पाइथन के साथ Google स्प्रेडशीट से वर्कशीट आईडी कैसे प्राप्त करें?

एक विधि मैं पाई है तो Google स्प्रेडशीट का एक्सएमएल खींचने के लिए this question के अनुसार, एक ही रास्ता के बाद से है है वर्कशीट आईडी प्राप्त करने के लिए एक वर्कशीट के एक्सएमएल नीचे स्ट्रीम करने के लिए है, लेकिन उदाहरण जावास्क्रिप्ट में है और मैं अजगर

में ऐसा करने की जरूरत यह जावा स्क्रिप्ट कोड है कि मैं पायथन में अमल करना चाहते हैं:

Dim worksheetFeed As WorksheetFeed 
    Dim query As WorksheetQuery 
    Dim worksheet As WorksheetEntry 
    Dim output As New MemoryStream 
    Dim xml As String 
    Dim gid As String = String.Empty 

    Try 
    _service = New Spreadsheets.SpreadsheetsService("ServiceName") 
    _service.setUserCredentials(UserId, Password) 
    query = New WorksheetQuery(feedUrl) 
    worksheetFeed = _service.Query(query) 
    worksheet = worksheetFeed.Entries(0) 

    ' Save worksheet feed to memory stream so we can 
    ' get the xml returned from the feed url and look for 
    ' the gid. Gid allows us to download the specific worksheet tab 
    Using output 
     worksheet.SaveToXml(output) 
    End Using 

    xml = Encoding.ASCII.GetString(output.ToArray()) 

ऐसा लगता है कि Google स्प्रेडशीट से XML प्राप्त करने का सबसे अच्छा तरीका Gdata का उपयोग कर रहा है, इसलिए मैंने GData डाउनलोड किया है और मेरे क्रेडेंशियल्स के साथ the Google Spreadsheet example को आजमाया है।

नीचे

#!/usr/bin/python 
# 
# Copyright (C) 2007 Google Inc. 
# 
# Licensed under the Apache License, Version 2.0 (the "License"); 
# you may not use this file except in compliance with the License. 
# You may obtain a copy of the License at 
# 
#  http://www.apache.org/licenses/LICENSE-2.0 
# 
# Unless required by applicable law or agreed to in writing, software 
# distributed under the License is distributed on an "AS IS" BASIS, 
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
# See the License for the specific language governing permissions and 
# limitations under the License. 


__author__ = '[email protected] (Laura Beth Lincoln)' 


try: 
    from xml.etree import ElementTree 
except ImportError: 
    from elementtree import ElementTree 
import gdata.spreadsheet.service 
import gdata.service 
import atom.service 
import gdata.spreadsheet 
import atom 
import getopt 
import sys 
import string 


class SimpleCRUD: 

    def __init__(self, email, password): 
    self.gd_client = gdata.spreadsheet.service.SpreadsheetsService() 
    self.gd_client.email = '[email protected]' 
    self.gd_client.password = 'jkjkdioerzumawya' 
    self.gd_client.source = 'Spreadsheets GData Sample' 
    self.gd_client.ProgrammaticLogin() 
    self.curr_key = '' 
    self.curr_wksht_id = '' 
    self.list_feed = None 

    def _PromptForSpreadsheet(self): 
    # Get the list of spreadsheets 
    feed = self.gd_client.GetSpreadsheetsFeed() 
    self._PrintFeed(feed) 
    input = raw_input('\nSelection: ') 
    id_parts = feed.entry[string.atoi(input)].id.text.split('/') 
    self.curr_key = id_parts[len(id_parts) - 1] 

    def _PromptForWorksheet(self): 
    # Get the list of worksheets 
    feed = self.gd_client.GetWorksheetsFeed(self.curr_key) 
    self._PrintFeed(feed) 
    input = raw_input('\nSelection: ') 
    id_parts = feed.entry[string.atoi(input)].id.text.split('/') 
    self.curr_wksht_id = id_parts[len(id_parts) - 1] 

    def _PromptForCellsAction(self): 
    print ('dump\n' 
      'update {row} {col} {input_value}\n' 
      '\n') 
    input = raw_input('Command: ') 
    command = input.split(' ', 1) 
    if command[0] == 'dump': 
     self._CellsGetAction() 
    elif command[0] == 'update': 
     parsed = command[1].split(' ', 2) 
     if len(parsed) == 3: 
     self._CellsUpdateAction(parsed[0], parsed[1], parsed[2]) 
     else: 
     self._CellsUpdateAction(parsed[0], parsed[1], '') 
    else: 
     self._InvalidCommandError(input) 

    def _PromptForListAction(self): 
    print ('dump\n' 
      'insert {row_data} (example: insert label=content)\n' 
      'update {row_index} {row_data}\n' 
      'delete {row_index}\n' 
      'Note: No uppercase letters in column names!\n' 
      '\n') 
    input = raw_input('Command: ') 
    command = input.split(' ' , 1) 
    if command[0] == 'dump': 
     self._ListGetAction() 
    elif command[0] == 'insert': 
     self._ListInsertAction(command[1]) 
    elif command[0] == 'update': 
     parsed = command[1].split(' ', 1) 
     self._ListUpdateAction(parsed[0], parsed[1]) 
    elif command[0] == 'delete': 
     self._ListDeleteAction(command[1]) 
    else: 
     self._InvalidCommandError(input) 

    def _CellsGetAction(self): 
    # Get the feed of cells 
    feed = self.gd_client.GetCellsFeed(self.curr_key, self.curr_wksht_id) 
    self._PrintFeed(feed) 

    def _CellsUpdateAction(self, row, col, inputValue): 
    entry = self.gd_client.UpdateCell(row=row, col=col, inputValue=inputValue, 
     key=self.curr_key, wksht_id=self.curr_wksht_id) 
    if isinstance(entry, gdata.spreadsheet.SpreadsheetsCell): 
     print 'Updated!' 

    def _ListGetAction(self): 
    # Get the list feed 
    self.list_feed = self.gd_client.GetListFeed(self.curr_key, self.curr_wksht_id) 
    self._PrintFeed(self.list_feed) 

    def _ListInsertAction(self, row_data): 
    entry = self.gd_client.InsertRow(self._StringToDictionary(row_data), 
     self.curr_key, self.curr_wksht_id) 
    if isinstance(entry, gdata.spreadsheet.SpreadsheetsList): 
     print 'Inserted!' 

    def _ListUpdateAction(self, index, row_data): 
    self.list_feed = self.gd_client.GetListFeed(self.curr_key, self.curr_wksht_id) 
    entry = self.gd_client.UpdateRow(
     self.list_feed.entry[string.atoi(index)], 
     self._StringToDictionary(row_data)) 
    if isinstance(entry, gdata.spreadsheet.SpreadsheetsList): 
     print 'Updated!' 

    def _ListDeleteAction(self, index): 
    self.list_feed = self.gd_client.GetListFeed(self.curr_key, self.curr_wksht_id) 
    self.gd_client.DeleteRow(self.list_feed.entry[string.atoi(index)]) 
    print 'Deleted!' 

    def _StringToDictionary(self, row_data): 
    dict = {} 
    for param in row_data.split(): 
     temp = param.split('=') 
     dict[temp[0]] = temp[1] 
    return dict 

    def _PrintFeed(self, feed): 
    for i, entry in enumerate(feed.entry): 
     if isinstance(feed, gdata.spreadsheet.SpreadsheetsCellsFeed): 
     print '%s %s\n' % (entry.title.text, entry.content.text) 
     elif isinstance(feed, gdata.spreadsheet.SpreadsheetsListFeed): 
     print '%s %s %s' % (i, entry.title.text, entry.content.text) 
     # Print this row's value for each column (the custom dictionary is 
     # built using the gsx: elements in the entry.) 
     print 'Contents:' 
     for key in entry.custom: 
      print ' %s: %s' % (key, entry.custom[key].text) 
     print '\n', 
     else: 
     print '%s %s\n' % (i, entry.title.text) 

    def _InvalidCommandError(self, input): 
    print 'Invalid input: %s\n' % (input) 

    def Run(self): 
    self._PromptForSpreadsheet() 
    self._PromptForWorksheet() 
    input = raw_input('cells or list? ') 
    if input == 'cells': 
     while True: 
     self._PromptForCellsAction() 
    elif input == 'list': 
     while True: 
     self._PromptForListAction() 


def main(): 
    # parse command line options 
    try: 
    opts, args = getopt.getopt(sys.argv[1:], "", ["user=", "pw="]) 
    except getopt.error, msg: 
    print 'python spreadsheetExample.py --user [username] --pw [password] ' 
    sys.exit(2) 

    user = '[email protected]' 
    pw = 'fakepassword' 
    key = '' 
    # Process options 
    for o, a in opts: 
    if o == "--user": 
     user = a 
    elif o == "--pw": 
     pw = a 

    if user == '' or pw == '': 
    print 'python spreadsheetExample.py --user [username] --pw [password] ' 
    sys.exit(2) 

    sample = SimpleCRUD(user, pw) 
    sample.Run() 


if __name__ == '__main__': 
    main() 

देखें हालांकि इस निम्नलिखित त्रुटि देता है:

Traceback (most recent call last): 
    File "/Users/Chris/Desktop/gdata_test.py", line 200, in <module> 
    main() 
    File "/Users/Chris/Desktop/gdata_test.py", line 196, in main 
    sample.Run() 
    File "/Users/Chris/Desktop/gdata_test.py", line 162, in Run 
    self._PromptForSpreadsheet() 
    File "/Users/Chris/Desktop/gdata_test.py", line 49, in _PromptForSpreadsheet 
    feed = self.gd_client.GetSpreadsheetsFeed() 
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/gdata/spreadsheet/service.py", line 99, in GetSpreadsheetsFeed 
    converter=gdata.spreadsheet.SpreadsheetsSpreadsheetsFeedFromString) 
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/gdata/service.py", line 1074, in Get 
    return converter(result_body) 
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/gdata/spreadsheet/__init__.py", line 395, in SpreadsheetsSpreadsheetsFeedFromString 
    xml_string) 
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/atom/__init__.py", line 93, in optional_warn_function 
    return f(*args, **kwargs) 
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/atom/__init__.py", line 127, in CreateClassFromXMLString 
    tree = ElementTree.fromstring(xml_string) 
    File "<string>", line 125, in XML 
cElementTree.ParseError: no element found: line 1, column 0 
[Finished in 0.3s with exit code 1] 
[shell_cmd: python -u "/Users/Chris/Desktop/gdata_test.py"] 
[dir: /Users/Chris/Desktop] 
[path: /usr/bin:/bin:/usr/sbin:/sbin] 

मैं भी है कि मैं Google Spreadsheets के साथ बातचीत करने के लिए एक विधि के रूप Gspread उपयोग कर रहे हैं उल्लेख करना चाहिए, लेकिन जब मैं नीचे कोड चलाएं, मुझे ग्रिड मिलती है, लेकिन मुझे वर्कशीट आईडी होना चाहिए।

gc = gspread.authorize(credentials) 
sh = gc.open_by_url('google_spreadsheet_url') 
sh.get_id_fields() 
>> {'spreadsheet_id': '1BgCEn-3Nor7UxOEPwD-qv8qXe7CaveJBrn9_Lcpo4W4','worksheet_id': 'oqitk0d'} 

उत्तर

6

देखें self.gd_client.ProgrammaticLogin() कॉल - यह बड़ी समस्या है, क्योंकि यह "ClientLogin" प्राधिकरण विधि है जो पहले पदावनत किया गया था और बाद में removed on April 20, 2015 का उपयोग करता खड़ी कर रहा है।

मैं वास्तव में इसके बजाय अधिक ताजा और सक्रिय रूप से विकसित gspread मॉड्यूल में देखता हूं।


यहाँ है एक, कुछ हद तक पागल है, उदाहरण के प्रदर्शन कैसे एक दिया स्प्रेडशीट और कार्यपत्रक नाम के लिए वास्तविक "gid" मान प्राप्त करने के। ध्यान दें कि आपको सबसे पहले generate the JSON file with the OAuth credentials (मुझे लगता है कि आप पहले ही ऐसा कर चुके हैं) की आवश्यकता होगी।

कोड (जोड़ा टिप्पणी है कि उम्मीद है कि यह समझने में मदद करेंगे):

import urlparse 
import xml.etree.ElementTree as ET 

import gspread 
from oauth2client.service_account import ServiceAccountCredentials 

SPREADSHEET_NAME = 'My Test Spreadsheet' 
WORKSHEET_NAME = "Sheet2" 

PATH_TO_JSON_KEYFILE = '/path/to/json/key/file.json' 
NAMESPACES = {'ns0': 'http://www.w3.org/2005/Atom'} 
SCOPES = ['https://spreadsheets.google.com/feeds'] 

# log in 
credentials = ServiceAccountCredentials.from_json_keyfile_name(PATH_TO_JSON_KEYFILE, SCOPES) 
gss_client = gspread.authorize(credentials) 

# open spreadsheet 
gss = gss_client.open(SPREADSHEET_NAME) 

# extract the full feed url 
root = gss._feed_entry 
full_feed_url = next(elm.attrib["href"] for elm in root.findall("ns0:link", namespaces=NAMESPACES) if "full" in elm.attrib["href"]) 

# get the feed and extract the gid value for a given sheet name 
response = gss_client.session.get(full_feed_url) 
root = ET.fromstring(response.content) 
sheet_entry = next(elm for elm in root.findall("ns0:entry", namespaces=NAMESPACES) 
        if elm.find("ns0:title", namespaces=NAMESPACES).text == WORKSHEET_NAME) 
link = next(elm.attrib["href"] for elm in sheet_entry.findall("ns0:link", namespaces=NAMESPACES) 
      if "gid=" in elm.attrib["href"]) 

# extract "gid" from URL 
gid = urlparse.parse_qs(urlparse.urlparse(link).query)["gid"][0] 
print(gid) 

यह भी लग रहा है वहाँ एक रास्ता एक gid मूल्य के लिए कार्यपत्रक आईडी कन्वर्ट करने के लिए है की तरह, देखें:

+1

मैं वास्तव में जीस्प्रेड का उपयोग करता हूं और सबसे हालिया संस्करण है, और जीस्प्रेड मेरी समस्या की जड़ों में से एक है! मैंने gspread का उपयोग करके निम्नलिखित किया: gc.open_by_url (शीर्षक)। वर्कशीट (शीट_शीटल)।get_id_fields(), और यह यह देता है: {'spreadsheet_id': '1BgCEn-3Nor7UxOEPwD-qv8qXe7CaveJBrn9_Lcpo4W4', 'worksheet_id': 'oqitk0d'}। वह वर्कशीट_आईडी यूआरएल के भीतर वर्कशीट_आईडी नहीं है, जो मुझे चाहिए। नतीजतन, मुझे एक्सएमएल डेटा खींचने का सहारा लेना होगा। मैंने gspread मॉड्यूल के माध्यम से सभी को खोजा है और एक्सपीएल को जीस्प्रेड से खींचने में सक्षम नहीं है, लेकिन यह सबसे आदर्श परिदृश्य होगा – Chris

+0

@ क्रिस ठीक है, समझ गया, मुझे gspread के साथ प्रयोग करने दें और देखें कि क्या हम कर सकते हैं डब्ल्यूएस आईडी प्राप्त करें। – alecxe

+0

@Chris कृपया अपडेट की जांच करें। , फ़ाइल "/Users/Chris/Desktop/gspread_test.py", लाइन 35 जड़ = ET.fromstring (response.content) AttributeError में: Traceback (सबसे हाल कॉल पिछले): – alecxe

0

जम्मू 2017

आप नई Google स्प्रेडशीट एपीआई v4 का उपयोग कर सकते हैं। आप pygsheets लाइब्रेरी को देख सकते हैं जो एपीआई v4 का उपयोग करता है।

import pygsheets 

#authorize the pygsheets 
gc = pygsheets.authorize() 

#open the spreadsheet 
sh = gc.open('my new ssheet') 

# get the worksheet and its id  
print sh.worksheet_by_title("my test sheet").id 
संबंधित मुद्दे