此图显示了代码的结果: 上面是我的第一个文件,下面是我的第二个excel文件。
我尝试了多种选择(包括此选项):但对我而言不起作用,因为它在现有数据的下方创建了不同的条目。 我的标准是,我也想映射列名称,如果列名称相同,则追加数据,但不应覆盖以前的数据,只需追加。
import pandas as pd
import openpyxl
from openpyxl.reader.excel import load_workbook
df = pd.read_excel('input_data.xlsx',skiprows = 3)
append_df_to_excel('output_data.xlsx', df, sheet_name='Sheet1', index=False)
append_df_to_excel()用于在不覆盖的情况下将数据追加到现有文件中(但不匹配列名并相应地放置数据)
def append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None,
truncate_sheet=False,
**to_excel_kwargs):
from openpyxl import load_workbook
# ignore [engine] parameter if it was passed
if 'engine' in to_excel_kwargs:
to_excel_kwargs.pop('engine')
writer = pd.ExcelWriter(filename, engine='openpyxl')
# Python 2.x: define [FileNotFoundError] exception if it doesn't exist
try:
FileNotFoundError
except NameError:
FileNotFoundError = IOError
try:
# try to open an existing workbook
writer.book = load_workbook(filename)
# get the last row in the existing Excel sheet
# if it was not specified explicitly
if startrow is None and sheet_name in writer.book.sheetnames:
startrow = writer.book[sheet_name].max_row
# truncate sheet
if truncate_sheet and sheet_name in writer.book.sheetnames:
# index of [sheet_name] sheet
idx = writer.book.sheetnames.index(sheet_name)
# remove [sheet_name]
writer.book.remove(writer.book.worksheets[idx])
# create an empty sheet [sheet_name] using old index
writer.book.create_sheet(sheet_name, idx)
# copy existing sheets
writer.sheets = {ws.title:ws for ws in writer.book.worksheets}
except FileNotFoundError:
# file does not exist yet, we will create it
pass
if startrow is None:
startrow = 0
# write out the new sheet
df.to_excel(writer, sheet_name, startrow=startrow, **to_excel_kwargs)
# save the workbook
writer.save()
pandas dataframe merge()和concat()函数在这种情况下不起作用。
我阅读了很多帖子,但未能成功。如果有人提出解决方案,那就太好了。