将excel文件上载到sftp服务器

2024-09-19 23:40:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的代码,它将csv格式的df上传到sftp服务器

with sftp.open(mypath + timestr + '.csv', "w") as f:
    f.write(df_pdcs_ec.to_csv(index=False))

但是:有没有办法以excel格式上传相同的df

更新:我正试图根据@furas的回答生成包含两个选项卡的文件,但只得到一个选项卡

with sftp.open(mypath + timestr + '.xlsx', "wb") as f:
    df_pdcs_ec.to_excel(f, sheet_name = 'Test1', index=False)
    df_pdcs_ec.to_excel(f, sheet_name = 'Test2', index=False)

Tags: csvtofalsedfindexas格式with
1条回答
网友
1楼 · 发布于 2024-09-19 23:40:43

我不能测试它,但在Pandas中,所有函数都应该与file handlersfile-like objects一起工作,它们具有函数write(),因此您可以打开文件或连接并使用to_csv(file_handler){}等

但是对于excel您必须以字节模式写入它-wb

with sftp.open(mypath + timestr + '.csv', "wb") as f:
    df_pdcs_ec.to_csv(f, index=False)

with sftp.open(mypath + timestr + '.xlsx', "wb") as f:
    df_pdcs_ec.to_excel(f, index=False)

with sftp.open(mypath + timestr + '.html', "wb") as f:
    df_pdcs_ec.to_html(f, index=False)

编辑:

要保存多个选项卡,必须使用ExcelWriter(请参见文档:to_excel

我不能用sftp.open()测试它,但这应该可以。至少它可以与标准open()一起工作

with sftp.open(mypath + timestr + '.xlsx', "wb") as f:
    with pd.ExcelWriter(f) as writer:
        df_pdcs_ec.to_excel(writer, sheet_name='Test1', index=False)
        df_pdcs_ec.to_excel(writer, sheet_name='Test2', index=False)

相关问题 更多 >