使用Pandas将工作表添加到现有的Excel文件中 [英] Add worksheet to existing Excel file with pandas

查看:107
本文介绍了使用Pandas将工作表添加到现有的Excel文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

# Set the working folder to the same folder as the script
os.chdir(os.path.dirname(os.path.abspath(__file__)))

test = send_request().content
df = pd.read_csv(io.StringIO(test.decode('utf-8')))
writer = pd.ExcelWriter('NHL_STATS_JSB_final.xlsx', \
                        engine = 'xlsxwriter')
df.to_excel(writer, 'Player statistics', index=False)
writer.save()

我不明白为什么,但是我试图将工作表 Player statistics 添加到我当前的 NHL_STATS_JSB_final.xlsx 文件中,但是它不起作用.我的代码没有将工作表添加到文件中,而是使用当前文件并擦除所有先前的工作表以添加新的工作表.

I don't understand why, but I am trying to add the worksheet Player statistics to my current NHL_STATS_JSB_final.xlsx file, but it is not working. Instead of adding the worksheet to the file, my code use the current file and erase all previous worksheet to add the new one.

如何通过删除所有其他工作表将播放器统计信息添加到当前的Excel文件中?

How could I add Player statistics to my current Excel file with erasing all other worksheets?

推荐答案

这是我的一个项目中的代码片段.这应该正是您想要的.您需要使用openpyxl而不是xlsxwriter来更新现有文件.

Here is a snippet of code from one of my projects. This should do exactly what you want. You need to use openpyxl rather than xlsxwriter to allow you to update an existing file.

writer = pd.ExcelWriter(file_name, engine='openpyxl')

if os.path.exists(file_name):
    book = openpyxl.load_workbook(file_name)
    writer.book = book

df.to_excel(writer, sheet_name=key)
writer.save()
writer.close()

这篇关于使用Pandas将工作表添加到现有的Excel文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆