Download Pandas DataFrame as an Excel file directly on Google Drive using PyDrive

I am trying to write pandas.DataFrame directly to Google Drive without first writing the file locally. I cannot find a solution and am not sure if this is possible. I 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: The DataFrame object does not have the attribute 'encode'

+5
source share
1 answer

You can get pandas to write the Excel file directly to a string, for example:

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 code above combined with your example. Please note that this part is not verified.

 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() 
+1
source

Source: https://habr.com/ru/post/1268679/


All Articles