0

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.

Deepan Das
  • 13
  • 5
  • Unrelated, but `client.Dispatch` can cause *late binding*, which can prevent correct type conversions in some corner cases, and give hard to find errors. `client.gencache.EnsureDispatch` forces early binding. More details on [this other SO post](https://stackoverflow.com/a/50163150/3545273) – Serge Ballesta Jun 29 '21 at 05:57
  • @SergeBallesta I tried all three methods described and it seems that `.gencache.EnsureDispatch` and `.Dispatch` have the same result (see screenshot I added in the answer below). – Алексей Р Jun 30 '21 at 04:37
  • @АлексейР: `EnsureDispatch` forces `win32com` to load all definitions for the COM object in a cache. Once the cache has been loaded, `Dispatch` will use it and you will get early binding. But it the cache has never been loaded, `Dispatch` will only give you a late binding proxy. – Serge Ballesta Jun 30 '21 at 06:36

1 Answers1

0

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()
Алексей Р
  • 7,507
  • 2
  • 7
  • 18
  • Thanks a lot! I think I am very close. Just imagine that I have already copied a data grid from a platform. If I paste it onto a blank excel sheet, the dataset looks like a normal/ regular excel sheet. Now, I would run the above code snippet after I am done copying the data grid. So, would it be okay to skip df and df.to_clipboard steps, and jump to [ wb.Activesheet.Paste(wb.Activesheet.Range("A1")) # paste data to Excel ]? If not, what should I do? Much appreciated. – Deepan Das Jun 29 '21 at 04:21
  • Also, while running, I get this error: '' object has no attribute 'Activesheet' – Deepan Das Jun 29 '21 at 04:27
  • Updated, see above – Алексей Р Jun 29 '21 at 04:50
  • Thanks a lot! It just worked the way I wanted! – Deepan Das Jun 30 '21 at 01:23