0

我试图搜索很多地方,但没有看到任何关于如何使用 xlutils 或 xlwt 和 python 删除 excel 文件中现有工作表的示例代码片段。请问谁能帮帮我?

4

4 回答 4

4

我刚刚处理了这个问题,虽然这通常不是一个好的编码选择,但您可以使用内部Workbook _worksheets 来访问和设置工作簿对象的工作表。

write_book._Workbook__worksheets = [write_book._Workbook__worksheets[0]]

这将剥离除与工作簿关联的第一个工作表之外的所有内容

于 2012-07-17T02:04:10.673 回答
2

我只是想确认我使用大卫给出的答案来工作。这是一个示例,说明我有一个包含 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))
于 2012-08-23T00:50:00.720 回答
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
于 2017-06-09T14:12:05.847 回答
-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 
于 2012-04-10T09:27:01.307 回答