I'm trying to add my DataFrame data to an existing Excel worksheet and instead, it's completely overwriting it and deleting all of my existing worksheets. Here's the warning message I get in my console:
UserWarning: File contains an invalid specification for Closed POA&M Items. This will be removed
warn(msg)
UserWarning: File contains an invalid specification for Open POA&M Items. This will be removed
warn(msg)
I'm just trying to add to my "Open POA&M Items" sheet using the following code:
curr_poam = "Reports/September.xlsx"
curr_closed_sheet = "Open POA&M Items"
def main():
writeToExcel(closed_items, curr_poam, curr_closed_sheet)
def writeToExcel(dataframe, path_to_current_poam, sheet_name):
with pd.ExcelWriter(path_to_current_poam, engine="openpyxl", mode='a', if_sheet_exists='overlay') as writer:
dataframe.to_excel(writer, sheet_name=sheet_name, startrow=5, index=False, header=4)
Here's what my Open worksheet looks like, which has all the headers and columns formatted
Is it possible to start writing to this worksheet from row 6, adding my DataFrame to it? Based off the Pandas docs I thought I could just use mode='a'
and if_sheet_exists='overlay'
to append to an existing worksheet, but instead it's just deleting all worksheets and creating a new one with just my DataFrame in it.
Solutions attempted:
So far tried the two solutions here Pandas mode='a', if_sheet_exists='overlay' not working
Updating Pandas and Openpyxl didn't fix this problem for my use-case
Neither did adding a start row to this line of code
dataframe.to_excel(writer, sheet_name=sheet_name, index=False, startrow=writer.sheets[sheet_name].max_row, header=None)
However, this did generate two new errors:
KeyError: 'Open POA&M Items'
IndexError: At least one sheet must be visible