将 Dataframe 附加到带有Pandas的excel

vawmfj5a  于 2023-03-16  发布在  其他
关注(0)|答案(7)|浏览(128)

我希望将 Dataframe 附加到excel
这段代码几乎可以按预期工作。虽然它不是每次都追加。我运行它,它把 Dataframe 放在excel中。但是每次我运行它,它都不追加。我还听说openpyxl是cpu密集型的,但没有听说过很多workarounds

import pandas
from openpyxl import load_workbook

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

df1.to_excel(writer, index = False)

writer.save()

我希望每次运行它时都追加数据,但这没有发生。
数据输出看起来像原始数据:

A   B   C
H   H   H

我想再跑一次

A   B    C
H   H    H
H   H    H

如果这是显而易见的,我对python很陌生,我练习的例子并没有像想要的那样工作,请道歉。
问题是-如何在每次运行时追加数据。我尝试更改xlsxwriter,但得到AttributeError: 'Workbook' object has no attribute 'add_format'

aiazj4mn

aiazj4mn1#

首先,这篇文章是解决方案的第一部分,在这里您应该指定startrow=:使用python panda将新 Dataframe 附加到现有Excel工作表
你也可以考虑header=False .所以它应该看起来像:

df1.to_excel(writer, startrow = 2,index = False, Header = False)

如果你想让它自动到达工作表的末尾并附加你的df,那么用途:

startrow = writer.sheets['Sheet1'].max_row

如果您希望它遍历工作簿中的所有工作表:

for sheetname in writer.sheets:
    df1.to_excel(writer,sheet_name=sheetname, startrow=writer.sheets[sheetname].max_row, index = False,header= False)

btw:对于writer.sheets,你可以使用字典理解(我认为它更简洁,但这取决于你,它产生相同的输出):

writer.sheets = {ws.title: ws for ws in book.worksheets}

因此完整代码为:

import pandas
from openpyxl import load_workbook

book = load_workbook('test.xlsx')
writer = pandas.ExcelWriter('test.xlsx', engine='openpyxl')
writer.book = book
writer.sheets = {ws.title: ws for ws in book.worksheets}

for sheetname in writer.sheets:
    df1.to_excel(writer,sheet_name=sheetname, startrow=writer.sheets[sheetname].max_row, index = False,header= False)

writer.save()
oxf4rvwz

oxf4rvwz2#

您可以使用append_df_to_excel()帮助器函数defined in this answer
用法示例:

filename = r'C:\OCC.xlsx'

append_df_to_excel(filename, df)

append_df_to_excel(filename, df, header=None, index=False)

append_df_to_excel(filename, df, sheet_name='Sheet2', index=False)

append_df_to_excel(filename, df, sheet_name='Sheet2', index=False, startrow=25)
goqiplq2

goqiplq23#

这里所有的例子都相当复杂,在documentation中要简单得多:

def append_to_excel(fpath, df, sheet_name):
    with pd.ExcelWriter(fpath, mode="a") as f:
        df.to_excel(f, sheet_name=sheet_name)

append_to_excel(<your_excel_path>, <new_df>, <new_sheet_name>)

当在LibreOffice/OpenOffice excel文件上使用这个时,我得到错误:

KeyError: "There is no item named 'xl/drawings/drawing1.xml' in the archive"

这是openpyxl中的一个bug,如所提到的here

bnlyeluc

bnlyeluc4#

我试着读取一个excel,把它放到一个数据框中,然后把excel中的数据框与所需的数据框连接起来,这对我很有效。

def append_df_to_excel(df, excel_path):
    df_excel = pd.read_excel(excel_path)
    result = pd.concat([df_excel, df], ignore_index=True)
    result.to_excel(excel_path, index=False)

df = pd.DataFrame({"a":[11,22,33], "b":[55,66,77]})
append_df_to_excel(df, r"<path_to_dir>\<out_name>.xlsx")
zd287kbt

zd287kbt5#

如果有人需要它,我找到了一个更简单的方法:

将DF转换为列表中的行
rows = your_df.values.tolist()
加载您的工作簿
workbook = load_workbook(filename=your_excel)
挑选你的床单
sheet = workbook[your_sheet]
循环访问要追加的每一行:
for row in rows:
    sheet.append(row)
完成后保存工作簿
workbook.save(filename=your_excel)
把所有这些放在一起:
rows = your_df.values.tolist()
workbook = load_workbook(filename=your_excel)
sheet = workbook[your_sheet]
for row in rows:
    sheet.append(row)
workbook.save(filename=your_excel)
lzfw57am

lzfw57am6#

def append_to_excel(fpath, df):
 if (os.path.exists(fpath)):
    x=pd.read_excel(fpath)
 else :
    x=pd.DataFrame()

 dfNew=pd.concat([df,x])
 dfNew.to_excel(fpath,index=False)
jqjz2hbq

jqjz2hbq7#

为什么要复杂化呢?只需在excel文件中获取行数,以确定在哪里追加startrow参数:

import pandas as pd
import openpyxl as xl

# Get number of rows in excel file (to determine where to append)
source_file = xl.load_workbook("file.xlsx", enumerate)
sheet = source_file["sheetname"]
row_count = sheet.max_row
source_file.close()

with pd.ExcelWriter("file.xlsx", mode='a', if_sheet_exists='overlay') as writer:  
    data.to_excel(writer, sheet_name='sheetname', index= False, startrow = row_count)

相关问题