2012-08-07 4 views
4

저는 파이썬 스크립트와 gdata 라이브러리를 사용하여 값으로 채울 Google 스프레드 시트를 가지고 있습니다. 스크립트를 두 번 이상 실행하면 워크 시트에 새 행이 추가됩니다. 스크립트를 실행하기 전에 먼저 행에서 모든 데이터를 지우고 싶습니다. 그런 식으로 데이터를 새로 고칩니다. 스크립트. 내가 사용하려고했습니다 :데이터를 추가하기 전에 파이썬 gdata를 사용하여 워크 시트의 행을 지 웁니다.

UpdateCell(row, col, value, spreadsheet_key, worksheet_id) 

을하지만,이 같은 루프에 대한 두 가지를 실행의 짧은 깨끗한 방법은 무엇입니까? 또한이 루프는 끔찍하게 느린 것 같다 :

for x in range(2, 45): 
     for i in range(1, 5): 
     self.GetGDataClient().UpdateCell(x, i, '', 
             self.spreadsheet_key, 
             self.worksheet_id) 

답변

11

확실하지 당신이 정리 여부,하지만 현재 데이터에서 청산을 가속화 관련하는 batch request를 사용해보십시오있어합니다. 예를 들어, 시트에있는 모든 단일 셀을 취소, 당신이 할 수 있습니다 :

cells = client.GetCellsFeed(key, wks_id) 
batch_request = gdata.spreadsheet.SpreadsheetsCellsFeed() 

# Iterate through every cell in the CellsFeed, replacing each one with '' 
# Note that this does not make any calls yet - it all happens locally 
for i, entry in enumerate(cells.entry): 
    entry.cell.inputValue = '' 
    batch_request.AddUpdate(cells.entry[i]) 

# Now send the entire batchRequest as a single HTTP request 
updated = client.ExecuteBatch(batch_request, cells.GetBatchLink().href) 

당신이 (그들은 첫 번째 행에있는 가정) 열 머리글을 저장 등의 작업을 수행하려는 경우, 당신은 CellQuery을 사용할 수 있습니다 :

# Set up a query that starts at row 2 
query = gdata.spreadsheet.service.CellQuery() 
query.min_row = '2' 

# Pull just those cells 
no_headers = client.GetCellsFeed(key, wks_id, query=query) 

batch_request = gdata.spreadsheet.SpreadsheetsCellsFeed() 

# Iterate through every cell in the CellsFeed, replacing each one with '' 
# Note that this does not make any calls yet - it all happens locally 
for i, entry in enumerate(no_headers.entry): 
    entry.cell.inputValue = '' 
    batch_request.AddUpdate(no_headers.entry[i]) 

# Now send the entire batchRequest as a single HTTP request 
updated = client.ExecuteBatch(batch_request, no_headers.GetBatchLink().href) 

또는이 기능을 사용하여 셀을 업데이트 할 수도 있습니다. 원하는대로 더 많이 업데이트 할 수 있습니다. 문서에 대한 링크는 링크를 변경하는 경우 문서에서 복사 한 기본 방법을 제공합니다.

import gdata.spreadsheet 
import gdata.spreadsheet.service 

client = gdata.spreadsheet.service.SpreadsheetsService() 
# Authenticate ... 

cells = client.GetCellsFeed('your_spreadsheet_key', wksht_id='your_worksheet_id') 

batchRequest = gdata.spreadsheet.SpreadsheetsCellsFeed() 

cells.entry[0].cell.inputValue = 'x' 
batchRequest.AddUpdate(cells.entry[0]) 
cells.entry[1].cell.inputValue = 'y' 
batchRequest.AddUpdate(cells.entry[1]) 
cells.entry[2].cell.inputValue = 'z' 
batchRequest.AddUpdate(cells.entry[2]) 
cells.entry[3].cell.inputValue = '=sum(3,5)' 
batchRequest.AddUpdate(cells.entry[3]) 

updated = client.ExecuteBatch(batchRequest, cells.GetBatchLink().href) 
+0

끝내주세요! 자세한 답변을 주셔서 감사합니다. –

+0

@RotemTamir 문제 없습니다. 행복하게 도와 줬습니다! – RocketDonkey