简体   繁体   中英

How to delete an existing worksheet in excel file using xlutils, xlwt, xlrd with python

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?

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

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))

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

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM