Using Panda Dataframes, I would like to compare two DFs and update the excel sheet. The problem, I'm seeing from my code, it only appends new row. It doesn't update pervious row. For example: DF1:
{'Sheet1': [{'ID': 1.0, 'NAME': 'hostname1', 'IP_ADDRESS': '192.168.1.1', 'STATUS': 'completed'}, {'ID': 2.0, 'NAME': 'hostname2', 'IP_ADDRESS': '192.168.1.2', 'STATUS': 'completed'}, {'ID': 3.0, 'NAME': 'hostname3', 'IP_ADDRESS': '192.168.1.3', 'STATUS': 'in_progress'}, {'ID': 4.0, 'NAME': 'hostname4', 'IP_ADDRESS': '192.168.1.4', 'STATUS': 'completed'}]}
DF2:
{'Sheet1': [{'ID': 1.0, 'NAME': 'hostname1', 'IP_ADDRESS': '192.168.1.1', 'STATUS':
'completed'}, {'ID': 2.0, 'NAME': 'hostname2', 'IP_ADDRESS': '192.168.1.2', 'STATUS': 'problem'}, {'ID': 3.0, 'NAME': 'hostname3', 'IP_ADDRESS': '192.168.1.3', 'STATUS': 'rma'}, {'ID': 4.0, 'NAME': 'hostname4', 'IP_ADDRESS': '192.168.1.4', 'STATUS': 'completed'},
{'ID': 5.0, 'NAME': 'hostname5', 'IP_ADDRESS': '192.168.1.5', 'STATUS': 'future'}]}
As you can see DF2 has different values.
here is the code, it show two DFs are different but doesn't updates the sheet.
def writexlsx_multi_sheets(filename, data, sheet_name, **to_excel_kwargs):
from openpyxl import load_workbook
orginalDF = pd.read_excel(filename, sheet_name=sheet_name, index=False)
newDF = pd.DataFrame.from_dict(data)
if 'engine' in to_excel_kwargs:
to_excel_kwargs.pop('engine')
writer = pd.ExcelWriter(filename, engine='openpyxl')
writer.book = load_workbook(filename)
writer.sheets = {ws.title:ws for ws in writer.book.worksheets}
if not orginalDF.equals(newDF):
result = orginalDF.combine_first(newDF)
result.to_excel(writer, sheet_name=sheet_name, index=False)
writer.save()
else:
return False