简体   繁体   English

Python - 使用 win32com.client 将 Excell 单元格范围格式化为表格

[英]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)

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM