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

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

问题描述

我对编程/python 比较陌生,所以如果能得到任何帮助,我将不胜感激.我想通过 COM 使用 Excel 将 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 对象的参考资料.我对如何访问 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 对象而不是应用程序对象本身 按照埃里克的建议.这让您可以像在 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天全站免登陆