Python-使用win32com.client将Excell单元格范围格式化为表格 [英] Python - Using win32com.client to format an Excell cell range as table

查看:135
本文介绍了Python-使用win32com.client将Excell单元格范围格式化为表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,该函数选择工作表中的所有非空单元格,将列宽调整为内容,并将其设置为表格格式.

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"

这篇关于Python-使用win32com.client将Excell单元格范围格式化为表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆