使用PyDrive将Pandas DataFrame作为Excel文件直接上传到Google云端硬盘

时间:2017-06-08 20:33:07

标签: python excel pandas openpyxl pydrive

我正在尝试将pandas.DataFrame直接写入Google云端硬盘,而无需先在本地写入文件。我找不到解决方案,也不确定它是否可行。我已经尝试了下面的代码,但我得到了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'对象没有属性'encode'

1 个答案:

答案 0 :(得分:1)

可以让pandas直接将Excel文件写入字符串,如:

代码:

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

完整代码:

以上代码结合您的示例。请注意,此部分未经测试。

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()