views:

153

answers:

3

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()

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.

Thanks!

A: 

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.

Eric Palakovich Carr
Unfortunately, there is no constants object for Excel.
behindalens
+1  A: 

All of the file format constants are documented here

SqlACID
That's the solution I'm using now. I've seen this problem before in other COM object interaces where there isn't proper documentation. I know the name of the constant, but not the value. I'm curious if there is a way to sidestep this.
behindalens
A: 

As a general rule I find it really useful to pre-write any code in the vba ide in Excel. This way you can find out all the values of constants etc that you need to use within your python code. You can also make sure stuff will work from within a more controlled environment.

Toby Allen