Last active
October 1, 2017 15:27
-
-
Save ijharulislam/81cb2481db4973390ec8fdf0f6cdfaf9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# requirements list | |
# gspread | |
#oauth2client | |
#PyOpenSSL | |
# DOC http://gspread.readthedocs.io/en/latest/oauth2.html | |
import gspread | |
from oauth2client.service_account import ServiceAccountCredentials | |
data = [{"Header1":"a", "Header2":"b"}, {"Header4":"a", "Header2":"b"}, {"Header1":"a", "Header2":"b"}, {"Header1":"a", "Header2":"b"}] | |
class GoogleDictWriter: | |
def __init__(self, credential_file, sheet, fieldnames, *args, **kwds): | |
""" | |
:param credential_file: Drive API secret file in JSON formate. | |
:param sheet_name: Google Drive spereadsheet name. | |
:param fieldnames: Heading list. | |
""" | |
self.fieldnames = fieldnames | |
scope = ['https://spreadsheets.google.com/feeds'] | |
credentials = ServiceAccountCredentials.from_json_keyfile_name(credential_file, scope) | |
gc = gspread.authorize(credentials) | |
self.wks = gc.open(sheet).sheet1 | |
def writeheader(self): | |
col = 0 | |
for field in self.fieldnames: | |
col += 1 | |
self.wks.update_cell(1, col, field) | |
def writerows(self, data): | |
row = 1 | |
for d in data: | |
row += 1 | |
col = 0 | |
for k, v in d.items(): | |
if k not in self.fieldnames: | |
raise ValueError("dict contains fields not in fieldnames: {}".format(k)) | |
col += 1 | |
self.wks.update_cell(row, col, v) | |
write = GoogleDictWriter('testsheet-23f8f3d172c9.json', 'test_sheet', data[0].keys()) | |
write.writeheader() | |
write.writerows(data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment