How to delete an existing worksheet in excel file

2019-08-02 23:01发布

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?

4条回答
\"骚年 ilove
2楼-- · 2019-08-02 23:18

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 
查看更多
看我几分像从前
3楼-- · 2019-08-02 23:28

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))
查看更多
孤傲高冷的网名
4楼-- · 2019-08-02 23:28

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
查看更多
爷的心禁止访问
5楼-- · 2019-08-02 23:33

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

查看更多
登录 后发表回答