我试图搜索很多地方,但是没有看到任何关于如何通过使用xlutils或xlwt和python删除excel文件中的现有工作表的代码片段。谁能帮助我呢?
答案 0 :(得分:3)
我刚刚解决了这个问题,虽然这通常不是一个好的编码选择,但您可以使用内部工作簿 _worksheets来访问和设置工作簿对象的工作表。
write_book._Workbook__worksheets = [write_book._Workbook__worksheets[0]]
除了与工作簿相关联的第一个工作表
之外,这将删除所有内容答案 1 :(得分:1)
我只是想确认一下,我使用David给出的答案来解决这个问题。这是一个示例,我有一个40多张表的电子表格(工作簿)需要拆分成他们自己的工作簿。我复制了除了一张纸之外的所有主工作簿并保存到新的电子表格中:
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))
答案 2 :(得分:1)
以下方法可满足您的需求:
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
答案 3 :(得分:-1)
不确定这些模块,但你可以试试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