alex_bn_lee

导航

[972] Remove specific sheets from an Excel file

To remove specific sheets from an Excel file, you can use the openpyxl library in Python. Here's how you can do it:

from openpyxl import load_workbook

# Path to the Excel file
excel_file_path = 'example.xlsx'

# Open the Excel workbook
wb = load_workbook(excel_file_path)

# List of sheet names to remove
sheets_to_remove = ['Sheet2', 'Sheet3']

# Iterate over the sheet names to remove
for sheet_name in sheets_to_remove:
    # Check if the sheet exists in the workbook
    if sheet_name in wb.sheetnames:
        # Remove the sheet from the workbook
        wb.remove(wb[sheet_name])

# Save the modified workbook
wb.save('updated_example.xlsx')

In this code:

  • load_workbook() loads the existing Excel workbook.
  • sheets_to_remove is a list containing the names of the sheets you want to remove.
  • We iterate over each sheet name in sheets_to_remove, check if it exists in the workbook using if sheet_name in wb.sheetnames, and remove it using wb.remove(wb[sheet_name]).
  • Finally, we save the modified workbook using wb.save().

posted on 2024-02-13 06:20  McDelfino  阅读(3)  评论(0编辑  收藏  举报