Reputation: 97
I am trying to load an existing Excel file and create a new sheet inside that workbook, but my code is not working using openpyxl
.
rb = load_workbook("C:\Raw_Dump.xlsx")
rb.create_sheet("Sheet2")
sheet1 = rb.worksheets[0]
Any help would be appreciated.
Upvotes: 4
Views: 28341
Reputation: 539
I spent a long time searching this and found the best way is to do sheet removal. The code below worked for me:
for sheet in wb.sheetnames:
if sheet not in "MY_SHEET_I_WANNA_KEEP":
rm_sheet = wb[sheet];
wb.remove_sheet(rm_sheet)
wb.save("JustOneSheet.xlsx")
Upvotes: 1
Reputation: 140148
You have to save
the workbook to the same filename:
rb.save(r"C:\Raw_Dump.xlsx")
full working example:
import openpyxl
ws_name = r"Raw_Dump.xlsx"
rb = openpyxl.load_workbook(ws_name)
rb.create_sheet("Sheet2")
rb.save(ws_name)
Upvotes: 8