gpt4 book ai didi

python - 如何将数据框附加到现有的 Excel 工作表?

转载 作者:行者123 更新时间:2023-11-28 21:45:41 31 4
gpt4 key购买 nike

该函数被多次调用。我一直在计数,这样如果它是第一次调用,就会创建一个工作簿。然后我使用 pd.ExcelWrite() 写入该工作簿。下次 else: 被执行并打开相同的工作簿。它的第一张纸被选中,它的最后一行被找到。 DataFrame 写在该行上。这是我的代码:

def WriteFile (df):
if count1 == 1:
workbook = xlsxwriter.Workbook('pandas_simple.xlsx')
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
df.to_excel(writer, index=False )
workbook.close()
else:
book = open_workbook('pandas_simple.xlsx')
sheet_names = book.sheet_names()
sheet = book.sheet_by_name(sheet_names[0])
row = sheet.nrows
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
df.to_excel(writer, index=False, header=False, startrow = row )

我得到这个异常:

Exception Exception: Exception('Exception caught in workbook destructor. Explicit close() 
may be required for workbook.',) in <bound method Workbook.__del__ of <xlsxwriter.workbook.Workbook
object at 0x000000000A143860>> ignored Exception

执行代码后,我的 pandas_simple.xlsx 也是空的。我究竟做错了什么?

最佳答案

感谢@ski。

请引用他和关于同一个问题

How to write to an existing excel file without overwriting data (using pandas)?

import pandas
from openpyxl import load_workbook

book = load_workbook('Masterfile.xlsx')
writer = pandas.ExcelWriter('Masterfile.xlsx', engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2'])

writer.save()

关于python - 如何将数据框附加到现有的 Excel 工作表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39068124/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com