将 pandas 数据框写入现有工作簿 [英] writing pandas data frame to existing workbook

查看:162
本文介绍了将 pandas 数据框写入现有工作簿的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将数据框保存到第二张文件,但是我不能这样做,我不知道为什么。

I want to save a data frame to the second sheet of a file but I can't do that and I don't know why.

yfile = openpyxl.load_workbook(new_file, data_only=True) 
ws = yfile.worksheets[0] 
sheet2 = yfile.create_sheet() 
ws2 = yfile.get_sheet_by_name("Sheet").title = "Analysis" 
writer = pd.ExcelWriter(yfile, engine='xlsxwriter') 
df3.to_excel(writer, sheet_name='Analysis') 
writer.save()
yfile.save(new_file)                                          

我已经创建了Analysis 但是当我保存它时,我收到以下响应:AttributeError:'Workbook'对象没有属性'write'

I have created the sheet 'Analysis' but when I save in it I received the following response: "AttributeError: 'Workbook' object has no attribute 'write'"

我需要修改什么? p>

What I have to modify?

推荐答案

你可以做的方式:

you can do it this way:

In [352]: fn = r'/path/to/your/excel.xlsx'

创建pandas excel作家对象

create pandas excel writer object

In [353]: writer = pd.ExcelWriter(fn, engine='openpyxl')

创建openpyxl书对象(稍后我们将需要)

create openpyxl book object (we will need it later on)

In [354]: book = load_workbook(fn)

大熊猫openpyxl的书给大熊猫作家。

assign pandas openpyxl's book to pandas writer.book

In [355]: writer.book = book

从openpyxl表创建pandas ExcelWriter表

create pandas ExcelWriter sheets from openpyxl sheets

In [356]: writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

将熊猫DF保存到新表格,保留旧的

saving pandas DF to new sheet, preserving old ones

In [357]: df.to_excel(writer, sheet_name='New')

关闭作者对象

In [358]: writer.save()

这篇关于将 pandas 数据框写入现有工作簿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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