Python 2.7:无法使用xlwt.Workbook._Workbook__worksheets删除工作表
我有一个工作簿,里面有12个工作表。我想创建一个新文件,删除其中的7个工作表。不过,我无法删除“OLD FILES”、“Licencias”和“HTM”这三个工作表。这是工作簿的一个示例, 这是我的代码。请帮我看看我哪里出错了。谢谢!
import xlrd, xlwt, xlutils.copy
#open the report, assign it to a variable
reporteWilly = xlrd.open_workbook('cctable.xls')
#create a writable copy of the report.
reporteWillyBk = xlutils.copy.copy(reporteWilly)
#Delete the sheets I dont want in the file
#by accessing the internal of the object xlwt.Workbook._Workbook_worksheets
#and there I'll specify only the elements I want in the sheets list:
#First I create a list of the worksheets available
okSheets = reporteWillyBk._Workbook__worksheets
#Then I remove from the list the sheets I don't want.
for sheet in okSheets:
if (sheet.name == "Guayaquil" or sheet.name== "Exports" or sheet.name == "OLD FILES"
or sheet.name == "Ecuador Holidays 2011" or sheet.name == "Licencias"
or sheet.name == "FILE LOCATION" or sheet.name == "HTM" ):
okSheets.remove(sheet)
#lastly I assing the good sheets I want to the collection.
reporteWillyBk._Workbook__worksheets = okSheets
#and save the new workbook.
reporteWillyBk.save ('cctableWilly.xls')
1 个回答
1
我有很好的经验使用 openpyxl
来完成这个任务
from openpyxl import load_workbook
wb = load_workbook('/path/to/your/workbook.xls')
print wb.get_sheet_names() #do this to double check your asking for the right sheet names
bad_sheets = ["Guayaquil","Exports","OLD FILES" ,"Ecuador Holidays 2011","Licencias","FILE LOCATION","HTM"]
#now delete the bad sheets
[wb.remove_sheet(wb.get_sheet_by_name(sheet)) for sheet in bad_sheets]
#if you get a ValueError, this means you are incorrectly requesting a sheet
wb.save('/some/other/name.xls')
祝你好运,希望这能帮到你