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

北城以北 提交于 2019-12-12 01:53:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!