Python excel如何查找默认文件扩展名

Python excel如何查找默认文件扩展名,python,excel,pywin32,Python,Excel,Pywin32,我正在尝试编写一个使用python和pywin32创建excel文件的应用程序,我希望使用默认格式和扩展名保存该文件,以供用户使用任何版本的excel。根据excel的版本,他们使用的默认格式可能是“Open XML工作簿”,它使用“.xlsx”扩展名。其他时候,它可能是基本的excel格式和“.xls”扩展名。此外,用户还可以配置excel以使用其他默认格式 我知道如何找到默认格式(Application.DefaultSaveFormat)——但我不知道如何确定该格式的默认扩展名。部分问题是

我正在尝试编写一个使用python和pywin32创建excel文件的应用程序,我希望使用默认格式和扩展名保存该文件,以供用户使用任何版本的excel。根据excel的版本,他们使用的默认格式可能是“Open XML工作簿”,它使用“.xlsx”扩展名。其他时候,它可能是基本的excel格式和“.xls”扩展名。此外,用户还可以配置excel以使用其他默认格式

我知道如何找到默认格式(Application.DefaultSaveFormat)——但我不知道如何确定该格式的默认扩展名。部分问题是我的文件名甚至在扩展名之前就有句点:
基本文件名为“filename.BOM”,因此实际文件名应为“filename.BOM.xls”或“filename.BOM.xlsx”,具体取决于默认格式

如果文件名中没有双句号,一切都会好起来。 因此,如果默认格式为“Open XML Workbook”,则Workbook.SaveAs(“文件名”)将创建一个名为“filename.xlsx”的文件。但是Workbook.SaveAs(“filename.BOM”)会创建一个名为“filename.BOM”的文件。当Excel看到文件名中已有句点时,不会添加默认扩展名

我唯一能弄明白的是保存一个临时文件,从中获取扩展名,然后删除临时文件——但这看起来真的很麻烦。谁有更好的解决方案

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

为什么不记录xlfileformats:extensions并使用它进行查找:

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
我只在示例dict中包含了最常见的格式,但是您可以从web上的许多源中充实它,例如。我没有输入KeyError异常处理程序,但您可能需要一个

祝你好运,
Mike

因为很难找到一个包含枚举、值和扩展的列表,所以我就是这样做的。棘手的部分是让枚举正常工作(参见代码)

以下是输出:

DefaultSaveFormat: 51

xlAddIn                            :    18, ".xls"
xlAddIn8                           :    18, ".xls"
xlCSV                              :     6, ".csv"
xlCSVMac                           :    22, ".csv"
xlCSVMSDOS                         :    24, ".csv"
xlCSVWindows                       :    23, ".csv"
xlCurrentPlatformText              : -4158, ".txt"
xlDBF2                             :     7, could not save this format
xlDBF3                             :     8, could not save this format
xlDBF4                             :    11, could not save this format
xlDIF                              :     9, ".dif"
xlExcel12                          :    50, ".xlsb"
xlExcel2                           :    16, could not save this format
xlExcel2FarEast                    :    27, could not save this format
xlExcel3                           :    29, could not save this format
xlExcel4                           :    33, could not save this format
xlExcel4Workbook                   :    35, could not save this format
xlExcel5                           :    39, ".xls"
xlExcel7                           :    39, ".xls"
xlExcel8                           :    56, ".xls"
xlExcel9795                        :    43, could not save this format
xlHtml                             :    44, ".htm"
xlIntlAddIn                        :    26, could not save this format
xlIntlMacro                        :    25, could not save this format
xlOpenDocumentSpreadsheet          :    60, ".ods"
xlOpenXMLAddIn                     :    55, ".ods" !!! this one is not right !!!
xlOpenXMLTemplate                  :    54, ".xltx"
xlOpenXMLTemplateMacroEnabled      :    53, ".xltm"
xlOpenXMLWorkbook                  :    51, ".xlsx"
xlOpenXMLWorkbookMacroEnabled      :    52, ".xlsm"
xlSYLK                             :     2, ".slk"
xlTemplate                         :    17, ".xlt"
xlTemplate8                        :    17, ".xlt"
xlTextMac                          :    19, ".txt"
xlTextMSDOS                        :    21, ".txt"
xlTextPrinter                      :    36, ".prn"
xlTextWindows                      :    20, ".txt"
xlUnicodeText                      :    42, ""
xlWebArchive                       :    45, ".mht"
xlWJ2WD1                           :    14, could not save this format
xlWJ3                              :    40, could not save this format
xlWJ3FJ3                           :    41, could not save this format
xlWK1                              :     5, could not save this format
xlWK1ALL                           :    31, could not save this format
xlWK1FMT                           :    30, could not save this format
xlWK3                              :    15, could not save this format
xlWK3FM3                           :    32, could not save this format
xlWK4                              :    38, could not save this format
xlWKS                              :     4, could not save this format
xlWorkbookDefault                  :    51, ".xlsx"
xlWorkbookNormal                   : -4143, ".xls"
xlWorks2FarEast                    :    28, could not save this format
xlWQ1                              :    34, could not save this format
xlXMLSpreadsheet                   :    46, ".xml"
我不知道为什么它不能保存一些格式;但它们看起来不像是非常普通或有用的

而且,xlOpenXMLAddIn格式非常奇怪。它报告并扩展了“.ods”-但这并不是它实际保存的内容。如果删除已创建的任何文件,请将代码更改为仅使用xlOpenXMLAddIn格式运行一次

import win32com
from os.path import splitext
from time import sleep

xl = win32com.client.gencache.EnsureDispatch( "Excel.Application")
app = xl.Application
app.Visible = 1
book = app.Workbooks.Add(); book.Activate()
constants = win32com.client.constants

formatName = 'xlOpenXMLAddIn'
formatNum = getattr( constants, formatName)
print 'test_file_format: %s > %s' % ( formatName, formatNum)

app.DisplayAlerts = False
try: book.SaveAs( r'C:\excel_file_formats\xlbook', formatNum)
except Exception: print 'could not save this format'
else:
    wbname, wbext = splitext( book.Name)
    print '"%s" > "%s"' % ( wbname, wbext)
你得到这个:

test_file_format: xlOpenXMLAddIn > 55
"Book1" > ""

它创建的文件将命名为“xlbook.xlam”;但是excel的标题栏上写着“Book1-MicrosoftExcel”。所以我不确定这是怎么回事。无论如何,它似乎不是一种非常有用的格式。

使用
.xls
,所有版本的Excel都会支持它。与其删除临时文件并以其他名称再次保存,为什么不直接重命名它?“与其删除临时文件,为什么不直接重命名它?”-因为只要excel打开文件,您就不能重命名或删除它,因为excel对该文件有一个锁定。我正在寻找一种更直接的方法来查找扩展名。但是,我认为这比保存临时文件更干净。另外,您提供的链接显示了每种格式的枚举,但没有提供扩展名。我已经搜索过了,一张显示两者的表格有点难找到——这很奇怪。不过我会解决的。感谢MikeYes,您必须从xlFileFormat常量计算扩展名,很难找到列表。但一旦你建立了自己的dict,你就拥有了它。
test_file_format: xlOpenXMLAddIn > 55
"Book1" > ""