How do I import a COM object namespace/enumeration in Python?(如何在 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 对象命名空间/枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Python 中导入 COM 对象命名空间/枚举?
基础教程推荐
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
