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

查看:267
本文介绍了如何在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天全站免登陆