1

I am trying to autofit the columns in my python generated xlsx file. Found the code from here[https://stackoverflow.com/a/33665967/5518944], but getting an exception. I am using Microsoft Office 2015.

Using this code:

import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')

ends up in following error:

[...]Python36\lib\site-packages\win32com\client\gencache.py", line 236, in GetModuleForCLSID
    __import__(sub_mod_name)
ModuleNotFoundError: No module named 'win32com.gen_py.00020813-0000-0000-C000-000000000046x0x1x8._Application'

Are you able to help me with this problem?

Poppypraun
  • 31
  • 4

1 Answers1

1

I can access and edit .xlsx files using:

from win32com.client import Dispatch
xl = Dispatch("Excel.Application")
wb = xl.Workbooks.Open(Filename="yourfile.xlsx")
ws = wb.Worksheets(1)

etc..

But i'm not sure if you really need EnsureDispatch, see this for mor about the differences.

xph
  • 937
  • 3
  • 8
  • 16
  • I tried your code (only first two lines), but this results in the same error on my side. Maybe anything missing in my installation? – Poppypraun May 16 '19 at 08:36
  • Oh. I use Python 3.7 and used pip to install `pywin32`, that is mandatory. And i work with Excel 2013, btw. People mention it could be a good idea to pip-install `pypiwin32` too, maybe worth a try? – xph May 16 '19 at 08:48
  • see [here](https://grokbase.com/t/python/python-win32/127hc7eagz/new-pywin32-errors-stating-object-has-no-attribute-and-the-code-worked-previously#20120717vfbmkovr77dlld3z2xkowieu6q) , this advice to delete `\win32com\gen_py` was also in the link in this answer. –  May 16 '19 at 12:08