简体   繁体   English

如何使用 xlutils、xlwt、xlrd 和 python 删除 excel 文件中的现有工作表

[英]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?我尝试搜索很多地方,但没有看到任何关于如何使用 xlutils 或 xlwt 和 python 删除 excel 文件中现有工作表的示例代码片段。请问谁能帮助我?

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.我刚刚处理了这个问题,虽然这通常不是一个好的编码选择,但您可以使用内部工作簿_worksheets 来访问和设置工作簿 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.我只是想确认我是否使用 David 给出的答案使它起作用。 Here is an example of where I had a spreadsheet (workbook) with 40+ sheets that needed to be split into their own workbooks.这是一个示例,其中我有一个电子表格(工作簿),其中包含 40 多张工作表,需要拆分成它们自己的工作簿。 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不确定那些模块,但你可以尝试 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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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