import win32com.client
xl = win32com.client.Dispatch('Excel.Application')
wb = xl.Workbooks('Book1')
ws = wb.Worksheets('Sheet1')
cell = ws.Range('A1')
cell.SetValue(arg1 = 'test entry in Excel')
Above is a very simple python script to write something in Excel.
To run the above, you need Mark Hammond’s pywin32 to generate the PythonCOM package. Read O’Reilly’s Python Programming on Win32 for more information on what PythonCOM packages are.
Once you have installed pythonwin, start it and generate the python code for Excel like this:
1. Start PythonWin
2. Select MakePy
3. Select the Excel library
4. The python file is generated.
However, the generated file will not yet work. If you now type in the above code snippet, you will get an COM error:
com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -214735
2565), None)
The cause of the com_error is various, on one machine, it was due to some bug in the file.
Use your editor and open the generated python file, find all the ret = Dispatch lines …
ret = Dispatch(ret, 'Item', '{00020857-0000-0000-C000-000000000046}', UnicodeToString=0)
and replace with
ret = Dispatch(ret, 'Item', '{00020857-0000-0000-C000-000000000046}')
On another, it was because xl was linked to an Excel instance which was visible. I did this to make it show itself
xl.Visible = 1
