Creating workbook and worksheet using openpyxl

19,669

Solution 1

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)

Solution 2

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")
Share:
19,669
GAURAV CHHABRA
Author by

GAURAV CHHABRA

Updated on June 08, 2022

Comments

  • GAURAV CHHABRA
    GAURAV CHHABRA almost 2 years

    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.