I'm trying to write and application that creates excel files using python and pywin32 and I'd like to save the file using the default format and extension for whatever version of excel the user is using. Depending on the version of excel they are using the default format could be "Open XML Workbook" which uses the ".xlsx" extension. Other times it could be the basic excel format and ".xls" extension. Plus the user can configure excel to use some other default format.
I know how to find the default format (Application.DefaultSaveFormat) - but I can't figure out how to determine the default extension for that format. Part of the problem is that my file names tend to include periods even before the extension:
the basic file name is "filename.BOM" so the actual file name should be "filename.BOM.xls" or "filename.BOM.xlsx" depending on the default format.
If I didn't have the double period in the file name everything would be fine. So if the default format is "Open XML Workbook" Workbook.SaveAs( "filename") would create a file named "filename.xlsx". But Workbook.SaveAs( "filename.BOM") creates a file named exactly "filename.BOM". Excel does not add the default extension when it sees a period already in the file name.
The only thing I can figure out is to save a temporary file, get the extension from that, then delete the temporary file - but that seems really kludgey. Anyone have a better solution?
from tempfile import mktemp
from os import path
from os import remove as delfile
class excel:
def __init__( self):
self.app = DispatchEx( "Excel.Application" )
def saveas_default_ext_format( self, workbook, filename):
# filename - file name with path but without extension
tmpname = mktemp()
alerts = self.app.DisplayAlerts
self.app.DisplayAlerts = False
workbook.SaveAs( tmpname)
self.app.DisplayAlerts = alerts
tmpname = self.app.ActiveWorkbook.FullName
x, ext = path.splitext( tmpname)
fullname = filename + ext
workbook.SaveAs( fullname)
delfile( tmpname)
return fullname
Why not make a dict of xlfileformats:extensions and use that to do a lookup:
from tempfile import mktemp
from os import path
from os import remove as delfile
class excel:
def __init__( self):
self.app = DispatchEx( "Excel.Application" )
self.dct = {51:'xlsx',
52:'xlsm',
50:'xlsb',
56:'xls'
}
def saveas_default_ext_format( self, workbook, filename):
# filename - file name with path but without extension
fullname = '.'.join((filename, self.dct[self.app.DefaultSaveFormat]))
workbook.SaveAs( fullname)
return fullname
I've only included the most common formats in the sample dict, but you can flesh it out from a number of sources on the web, like here. I didn't put in an KeyError exception handler, but you'll probably want one.
good luck, Mike