Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload a Pandas DataFrame as Excel file directly to Google Drive using PyDrive

I'm trying to write a pandas.DataFrame directly to Google Drive, without first writing the file out locally. I can't find a solution and not sure if it is even possible. I've tried the code below, but I get an AttributeError.

import pandas as pd
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
gauth.LoadCredentialsFile(mycreds)
drive = GoogleDrive(gauth)

df = pd.DataFrame({'a':[1,2],'b':[2,3]})

f = drive.CreateFile({'id': '0B_6_uVX9biFuX0FJWFkt'}) #test.xlsx file
f.SetContentString(df) 
f.Upload()

AttributeError: 'DataFrame' object has no attribute 'encode'

like image 470
cyril Avatar asked Nov 08 '22 21:11

cyril


1 Answers

It is possible to get pandas to write an Excel file directly to a string like:

Code:

wb = Workbook()
writer = pd.ExcelWriter('', engine='openpyxl')
writer.book = wb
df.to_excel(writer)
file_as_string = save_virtual_workbook(wb)

Full Code:

Here is the above code combined with your example. Please note that this part is untested.

import pandas as pd
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
gauth.LoadCredentialsFile(mycreds)
drive = GoogleDrive(gauth)

df = pd.DataFrame({'a': [1, 2], 'b': [2, 3]})

from openpyxl.workbook import Workbook
from openpyxl.writer.excel import save_virtual_workbook

wb = Workbook()
writer = pd.ExcelWriter('', engine='openpyxl')
writer.book = wb
df.to_excel(writer)

f = drive.CreateFile({'id': '0B_6_uVX9biFuX0FJWFkt'}) #test.xlsx file
f.SetContentString(save_virtual_workbook(wb))
f.Upload()
like image 63
Stephen Rauch Avatar answered Nov 14 '22 22:11

Stephen Rauch