Search code examples
pythonexcelwin32com

Python - Using win32com.client to format an Excell cell range as table


I'm trying to write a function that selects all non empty cells in a worksheet, adjust column width to content, and format them as table.

I am stuck on the last point, here's my current code:

import win32com.client
from win32com.client import constants


f = r"D:\Project\test_copy.xlsx"

exc = win32com.client.gencache.EnsureDispatch("Excel.Application")
exc.Visible = 1
exc.Workbooks.Open(Filename=f)
exc.ActiveSheet.UsedRange.Select()
exc.Selection.Columns.AutoFit()
exc.ActiveSheet.ListObjects("Table1").TableStyle ="TableStyleLight8"

The problem is with the very last line. I'm not sure what to do as the error message is very cryptic.

*snip*
 line 80, in __call__
    ret = self._oleobj_.InvokeTypes(0, LCID, 2, (9, 0), ((12, 1),),Index
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352565), None)

Solution

  • I got it and sharing with the community:

    import win32com.client
    from win32com.client import constants
    
    
    f = r"D:\Project\test_copy.xlsx"
    
    exc = win32com.client.gencache.EnsureDispatch("Excel.Application")
    exc.Visible = 1
    exc.Workbooks.Open(Filename=f)
    exc.ActiveSheet.UsedRange.Select()
    exc.Selection.Columns.AutoFit()
    exc.ActiveSheet.ListObjects.Add().TableStyle = "TableStyleMedium15"