How to delete an existing worksheet in excel file

2019-08-02 22:52发布

问题:

I tried to search many places but dit not see any example snippet of code about how to delete an existing worksheet in excel file by using xlutils or xlwt with python. Who can help me, please?

回答1:

I just dealt with this and although this is not generally a good coding choice, you can use the internal Workbook_worksheets to access and set the worksheets for a workbook object.

write_book._Workbook__worksheets = [write_book._Workbook__worksheets[0]]

this would strip everything but the first worksheet associated with a Workbook



回答2:

I just wanted to confirm that I got this to work using the answer David gave. Here is an example of where I had a spreadsheet (workbook) with 40+ sheets that needed to be split into their own workbooks. I copied the master workbook removed all but the one sheet and saved to a new spreadsheet:

from xlrd import open_workbook
from xlutils import copy

workbook = open_workbook(filepath)

# Process each sheet
for sheet in workbook.sheets():
    # Make a copy of the master worksheet
    new_workbook = copy.copy(workbook)

    # for each time we copy the master workbook, remove all sheets except
    #  for the curren sheet (as defined by sheet.name)
    new_workbook._Workbook__worksheets = [ worksheet for worksheet in new_workbook._Workbook__worksheets if worksheet.name == sheet.name ]

    # Save the new_workbook based on sheet.name
    new_workbook.save('{}_workbook.xls'.format(sheet.name))


回答3:

The following method does what you need:

def deleteAllSheetBut(workingFolder, xlsxFILE, sheetNumberNotToDelete=1):
import win32com.client as win32
import os
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.Visible = False
excel.DisplayAlerts = False
wb = excel.Workbooks.Open( os.path.join( workingFolder, xlsxFILE ) )
for i in range(1, wb.Worksheets.Count):
    if i != sheetNumberNotToDelete:
        wb.Worksheets(i).Delete()
wb.Save()
excel.DisplayAlerts = True
excel.Application.Quit()
return


回答4:

not sure about those modules but u can try win32

from win32com import client
def delete(self, number = 1):
    """
    (if the sheet is the first use 1. -1 to use real number)
    example: r.delete(1)
    """
    sheetnumber = int(number) - 1