使用Panda获取df.to_excel(...)之后的excel文件

时间:2017-03-22 14:08:56

标签: python excel pandas firebase writer

我正在使用Pyrebase将我的文件上传到Firebase。

我有一个DataFrame df并将其转换为Excel文件,如下所示:

writer      = ExcelWriter('results.xlsx')
excelFile   = df.to_excel(writer,'Sheet1')

print(excelFile)

# Save to firebase
childRef        = "path/to/results.xlsx"

storage         = firebase.storage()
storage.child(childRef).put(excelFile)

但是,这会将Excel文件存储为零字节的Office电子表格。如果我运行writer.save(),那么我确实得到了相应的文件类型(xlsx),但它存储在我的服务器上(我想避免)。如何像writer.save()一样生成正确的文件类型?

注意:print(excelFile)会返回None

2 个答案:

答案 0 :(得分:2)

可以通过使用本地内存来解决:

# init writer
bio         = BytesIO()
writer      = pd.ExcelWriter(bio, engine='xlsxwriter')
filename    = "output.xlsx"

# sheets
dfValue.to_excel(writer, "sheetname")

# save the workbook
writer.save()
bio.seek(0)      

# get the excel file (answers my question)          
workbook    = bio.read()  
excelFile   = workbook

# save the excelfile to firebase
# see also issue: https://github.com/thisbejim/Pyrebase/issues/142
timestamp       = str(int(time.time()*1000));
childRef        = "/path/to/" + filename

storage         = firebase.storage()
storage.child(childRef).put(excelFile)
fileUrl         = storage.child(childRef).get_url(None)

答案 1 :(得分:1)

根据文档,你应该添加

writer.save()

source