如何在Python中导入COM对象名称空间/枚举? [英] How do I import a COM object namespace/enumeration in Python?

查看:237
本文介绍了如何在Python中导入COM对象名称空间/枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对编程/ python来说比较新,所以我很乐意得到任何帮助。我想使用Excel通过COM保存Excel文件作为特定格式。这是代码:

I'm relatively new to programming/python, so I'd appreciate any help I can get. I want to save an excel file as a specific format using Excel through COM. Here is the code:

import win32com.client as win32 

def excel():
    app = 'Excel'
    x1 = win32.gencache.EnsureDispatch('%s.Application' % app)
    ss = x1.Workbooks.Add()
    sh = ss.ActiveSheet
    x1.Visible = True
    sh.Cells(1,1).Value = 'test write'
    ss.SaveAs(Filename="temp.xls", FileFormat=56)
    x1.Application.Quit()

if __name__=='__main__':
    excel()

我的问题是如何指定FileFormat如果我不明确地知道它的代码?浏览文档我找到了关于FileFormat对象的引用。我无法访问 XlFileFormat对象并导入它,以便我可以找到它的枚举值。

My question is how do I specify the FileFormat if I don't explicitly know the code for it? Browsing through the documentation I find the reference at about a FileFormat object. I'm clueless on how to access the XlFileFormat object and import it in a way that I can find the enumeration value for it.

谢谢!

推荐答案

这个问题有点陈旧,对于那些从Google到达这个页面(像我一样),我的解决方案是通过 win32com.client.constants 对象而不是应用程序对象本身访问常量由Eric建议。这样可以像VBE一样使用枚举常量:

This question is a bit stale, but for those reaching this page from Google (as I did) my solution was accessing the constants via the win32com.client.constants object instead of on the application object itself as suggested by Eric. This lets you use enum constants just like in the VBE:

>>> import win32com.client
>>> xl = win32com.client.gencache.EnsureDispatch('Excel.Application')
>>> C = win32com.client.constants
>>> C.xlWorkbookNormal
-4143
>>> C.xlCSV
6
>>> C.xlErrValue
2015
>>> C.xlThemeColorAccent1
5

此外,除非您手动运行 makepy 实用程序,如果使用常规的 win32com.client.Dispatch(..)方法初始化应用程序,常量可能不可用,是我遇到的另一个问题。使用 win32com.client.gencache.EnsureDispatch(..)(作为提问者)如果需要,在运行时检查并生成Python绑定。

Also, unless you've manually run the makepy utility, the constants may not be available if initializing the application with the regular win32com.client.Dispatch(..) method, which was another issue I was having. Using win32com.client.gencache.EnsureDispatch(..) (as the questioner does) checks for and generates the Python bindings at runtime if required.

我发现这个ActiveState页面是有帮助的。

这篇关于如何在Python中导入COM对象名称空间/枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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