3

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)

1 Answer 1

7

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.