Reputation: 73
I am trying to delete first sheet in an excel workbook using win32com.client in python 3.7.0, code snippets provided, the code executes without any errors but the sheet is not deleted. Note that its a xlsm file.
I also tried using openpyxl, however it seems, it does not work well with xlsm files.
import win32com.client
excel = win32com.client.Dispatch("Excel.Application")
excel_file = excel.Workbooks.Open(full_filepath\filename.xlsm)
sheet = excel_file.Worksheets(1)
sheet.Delete()
excel.ActiveWorkbook.SaveAs(Filename=full_filepath\filename1.xlsm, FileFormat="52")
excel_file.Close(True)
On opening the saved file, I see no change, first sheet is still there, can somebody tell what I am doing wrong?
Upvotes: 0
Views: 5200
Reputation: 472
try to replace
sheet = excel_file.Worksheets(1)
sheet.Delete()
with
excel_file.Worksheets(1).Delete()
update at 2019-5-17:
I got how do deal with it. you need to add before delete
excel.DisplayAlerts=False
because when you delete, excel will prompt alert whether you want to delete or not,thus, disable the displayalerts will not show the alert. you can use
excel.visible=True
to view the excel file and process of action the win32com on excel.
the following is my code
import os
import win32com.client
full_filepath=os.path.dirname(os.path.realpath('__file__'))+'/'
excel = win32com.client.Dispatch("Excel.Application")
excel_file = excel.Workbooks.Open(full_filepath+'temp.xlsm')
excel.visible=True #you can choose to show it or not.
excel.DisplayAlerts=False
excel_file.Worksheets(1).Delete()
excel.ActiveWorkbook.SaveAs(Filename=full_filepath+'temp2.xlsm', FileFormat="52")
excel_file.Close(True)
Upvotes: 3