Search code examples
pythonexcelwin32com

How to open a blank excel sheet (not previously saved) using python?


I have come across this code snippet to open a blank outlook message window:

import win32com.client as client
outlook= client.Dispatch('Outlook.Application')
message= outlook.CreateItem(0)
message.Display()

Now, I am wondering whether using win32com.client I can open a blank excel sheet where I want to paste the dataset stored in clipboard, and after saving I want to close the excel sheet. I used to do this manually: copy dataset, open excel, paste in excel, save the excel, and close.

Much thanks.


Solution

  • Try this code:

    import win32com.client as client
    
    xl = client.Dispatch('Excel.Application')
    wb = xl.Workbooks.Add()  # create blank workbook
    # it is assumed that the clipboard already contains the data to be pasted on the sheet
    wb.Sheets(1).Paste(wb.Sheets(1).Range("A1"))  # paste data to Excel
    xl.DisplayAlerts = False # not to display a dialog box if a book with this name already exists
    wb.Close(True, r'c:\test123.xlsx')  # save & close workbook
    xl.Quit()