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 对象命名空间/枚举?
基础教程推荐
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
