7

我对编程/python 比较陌生,所以如果能得到任何帮助,我将不胜感激。我想通过 COM 使用 Excel 将 excel 文件保存为特定格式。这是代码:

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 对象并以我可以找到它的枚举值的方式导入它一无所知。

谢谢!

4

4 回答 4

9

这个问题有点陈旧,但对于那些从 Google 访问此页面的人(就像我所做的那样),我的解决方案是通过对象访问常量,而不是按照 Eric 的建议win32com.client.constants访问应用程序对象本身。这让您可以像在 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 绑定。

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

于 2011-03-24T01:10:52.663 回答
2

When I used COM to access quickbooks, I could reach the constants defined under a constants member of the object. The code looked something like this (you'll be intersted in the third line):

self._session_manager.OpenConnection2("",
                                      application_name,
                                      QBFC8Lib.constants.ctLocalQBD)

I'm not sure if this will work, but try this:

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=x1.constants.xlWorkbookNormal)
    x1.Application.Quit()

if __name__=='__main__':
    excel()

Replace xlWorkbookNormal with whatever format your trying to choose in the X1FileFormat web page you posted in your question.

于 2009-10-29T23:21:01.433 回答
1

所有文件格式常量都记录在这里

于 2009-10-29T23:49:30.633 回答
1

作为一般规则,我发现在 Excel 中预先记录 VBA IDE 中的任何代码非常有用。通过这种方式,您可以找出需要在 python 代码中使用的所有常量值等。您还可以确保在更受控的环境中工作。

于 2009-11-07T08:21:05.760 回答