簡體   English   中英

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

[英]How to delete an existing worksheet in excel file using xlutils, xlwt, xlrd with python

我嘗試搜索很多地方,但沒有看到任何關於如何使用 xlutils 或 xlwt 和 python 刪除 excel 文件中現有工作表的示例代碼片段。請問誰能幫助我?

我剛剛處理了這個問題,雖然這通常不是一個好的編碼選擇,但您可以使用內部工作簿_worksheets 來訪問和設置工作簿 object 的工作表。

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

這將刪除除與工作簿關聯的第一個工作表之外的所有內容

我只是想確認我是否使用 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))

以下方法可以滿足您的需要:

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

不確定那些模塊,但你可以嘗試 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