The following code works correctly the first time creating tabs x1 and x2 and fills with data. When executed again for new data it doesn't check if the tabs already exist and adds new erroneous tabs x11 and x21.
import pandas as pd
import numpy as np
from openpyxl import load_workbook
import os
filename = os.path.dirname(os.path.abspath(__file__))+ '\\Test_excel.xlsx' # path to current directory adding file name
book = load_workbook(filename)
writer = pd.ExcelWriter(filename, engine='openpyxl')
writer.book = book
x1 = np.random.randn(10, 4)
df1 = pd.DataFrame(x1)
x2 = np.random.randn(20, 2)
df2 = pd.DataFrame(x2)
df1.to_excel(writer, sheet_name = 'x1')
df2.to_excel(writer, sheet_name = 'x2')
writer.save()
writer.close()
I need it to overwrite the existing tabs data if the tab already exists otherwise create the tab. Any ideas?