问题
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. Google did not help much on this.
*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)
I would really appreciate a little help here...
回答1:
Thanks for nothing.
It drove me half nuts but I got it. 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"
来源:https://stackoverflow.com/questions/35501678/python-using-win32com-client-to-format-an-excell-cell-range-as-table