使用Gdata、Python Google电子表格Api clien插入单元格

2024-10-01 13:37:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试更新或插入单元格到谷歌电子表格中,这是我第一次使用googleapi和python,所以我可能做了一些noddy。。但我一辈子都看不到。在

当前,我的代码更新现有单元格,但不插入新单元格(空白单元格保持空白),当我注释掉时”batchRequest.AddInsert(新单元格)” 但当它留在我得到一个返回的状态代码500和一堆xml时,这没什么帮助。在

代码(部分)

def setRowEntries(self, cohort_key=None):
  cohort = self.GetCohort(cohort_key)

  gd_client = gdata.spreadsheet.service.SpreadsheetsService()
  gd_client.email = email
  gd_client.password = password
  gd_client.source = 'YOUR_APP_NAME'

  # LOGIN
  try:
    # log in
    gd_client.ProgrammaticLogin()
  except socket.sslerror, e:
    logging.error('Spreadsheet socket.sslerror: ' + str(e))
    return False

  # KEY FOR SHEET
  key = '0At**************************Gc'

  # LOOKUP FOR WORKSHEET KEY
  GID_TABLE = {
    'android_users_by_week_by_registration' : 'od6'
  }

  wksht_id =''
  wksht_id = GID_TABLE[cohort_key]

  #  create a cells feed and batch request
  cells = gd_client.GetCellsFeed(key, wksht_id)
  batchRequest = gdata.spreadsheet.SpreadsheetsCellsFeed()

  #TODO SET TITLE

  #resize worksheet
 # cells.col_count = len(cohort[0])
 # cells.row_count = len(cohort)

  rowcursor = 0
  for myrow in cohort:
    colcursor = 0
    #print ("row ::"+str(myrow))
    for mycell in myrow:
      #print ("cell::"+str(mycell))
      found = 0
      #print ("try and place"+str(rowcursor)+','+str(colcursor))
      for myentry in cells.entry:
        if ((int(myentry.cell.row) == int(rowcursor+1)) and (int(myentry.cell.col) == int(colcursor+1))):
          print "updating  "+myentry.cell.text+" to "+str(mycell)
          myentry.cell.inputValue = str(mycell)
          batchRequest.AddUpdate(myentry)
          found = 1

      if not found:
        print "inserting "+str(mycell)+" at Cell "+ str(rowcursor+1)+'_'+str(colcursor+1)
        newCell = gdata.spreadsheet.SpreadsheetsCell()
        newCell.cell = gdata.spreadsheet.Cell(inputValue=str(mycell), text=None, row=str(rowcursor+1), col=str(colcursor+1))
        print newCEll.inpu
        batchRequest.AddInsert(newCell)# the broken part
      colcursor = colcursor + 1
    rowcursor = rowcursor + 1

  updated = gd_client.ExecuteBatch(batchRequest, cells.GetBatchLink().href)

  if updated:
    print "Sucessfull!"+str(updated)
  else:
    print "Failed!"

错误(部分)

^{pr2}$

我发现googleapi文档很难理解,而且示例很少,而且范围太窄。如果你能告诉我我做错了什么那就太好了


Tags: keyclientcellcohortprintcellsgdspreadsheet