2012-11-15 53 views
3

我想寫和使用python和pywin32創建excel文件的應用程序,我想使用默認格式和擴展名保存該文件的用戶是什麼版本的excel使用。根據Excel的版本,他們使用的默認格式可以是使用「.xlsx」擴展名的「Open XML Workbook」。其他時候可能是基本的excel格式和「.xls」擴展名。此外,用戶可以配置Excel使用其他一些默認格式。excel如何找到默認文件擴展名

我知道如何找到默認格式(Application.DefaultSaveFormat) - 但我無法弄清楚如何確定該格式的默認擴展名。部分問題是我的文件名往往會在擴展名前包含句點:
基本文件名是「filename.BOM」,所以實際文件名應該是「filename.BOM.xls」或「filename.BOM」。 xlsx「取決於默認格式。

如果我沒有在文件名稱中的雙重句點,一切都會好起來的。 因此,如果默認格式爲「Open XML Workbook」,Workbook.SaveAs(「filename」)將創建一個名爲「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 
+0

使用'.xls',所有版本的Excel都會遵守它。 –

+0

而不是刪除臨時文件並以不同的名稱再次保存,爲什麼不重命名它? 「 – l4mpi

+0

」而不是刪除臨時文件,爲什麼不重新命名呢?「 - 因爲只要excel打開文件,就不能重命名或刪除文件,因爲excel對文件有鎖定。 – GarybCoder

回答

0

何不做的xlfileformats一個字典:擴展和使用進行查找:

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 

我只包含的樣本字典中最常見的格式,但你可以充實其來自網絡上的多個來源,如here。我沒有放置一個KeyError異常處理程序,但您可能需要一個。

好運, 邁克

+0

我正在尋找更直接的方式來查找擴展名。不過,我認爲這比保存臨時文件更清潔。附:您提供的鏈接顯示每種格式的枚舉,但不提供擴展名。我搜索了一張表格,兩張表格都很難找到 - 這很奇怪。儘管如此,我會解決這個問題。謝謝Mike – GarybCoder

+0

是的,你必須從xlFileFormat常量中找出擴展名,很難找到一個列表。但是,一旦你建立你的字典,那麼你已經掌握了它。 – MikeHunter

4

由於包含在同一個地方的枚舉值和擴展列表是很難找到的,在這裏我做的方式。最棘手的部分是獲得枚舉的工作(見代碼)

import win32com 
from os.path import splitext 

XlFileFormats = [ 
    'xlAddIn'      , # Microsoft Excel 97-2003 Add-In 
    'xlAddIn8'      , # Microsoft Excel 97-2003 Add-In 
    'xlCSV'      , # CSV 
    'xlCSVMac'      , # Macintosh CSV 
    'xlCSVMSDOS'     , # MSDOS CSV 
    'xlCSVWindows'     , # Windows CSV 
    'xlCurrentPlatformText'  , # Current Platform Text 
    'xlDBF2'      , # DBF2 
    'xlDBF3'      , # DBF3 
    'xlDBF4'      , # DBF4 
    'xlDIF'      , # DIF 
    'xlExcel12'     , # Excel12 
    'xlExcel2'      , # Excel2 
    'xlExcel2FarEast'    , # Excel2 FarEast 
    'xlExcel3'      , # Excel3 
    'xlExcel4'      , # Excel4 
    'xlExcel4Workbook'    , # Excel4 Workbook 
    'xlExcel5'      , # Excel5 
    'xlExcel7'      , # Excel7 
    'xlExcel8'      , # Excel8 
    'xlExcel9795'     , # Excel9795 
    'xlHtml'      , # HTML format 
    'xlIntlAddIn'     , # International Add-In 
    'xlIntlMacro'     , # International Macro 
    'xlOpenDocumentSpreadsheet' , # OpenDocument Spreadsheet 
    'xlOpenXMLAddIn'    , # Open XML Add-In 
    'xlOpenXMLTemplate'   , # Open XML Template 
    'xlOpenXMLTemplateMacroEnabled', # Open XML Template Macro Enabled 
    'xlOpenXMLWorkbook'   , # Open XML Workbook 
    'xlOpenXMLWorkbookMacroEnabled', # Open XML Workbook Macro Enabled 
    'xlSYLK'      , # SYLK 
    'xlTemplate'     , # Template 
    'xlTemplate8'     , # Template 8 
    'xlTextMac'     , # Macintosh Text 
    'xlTextMSDOS'     , # MSDOS Text 
    'xlTextPrinter'    , # Printer Text 
    'xlTextWindows'    , # Windows Text 
    'xlUnicodeText'    , # Unicode Text 
    'xlWebArchive'     , # Web Archive 
    'xlWJ2WD1'      , # WJ2WD1 
    'xlWJ3'      , # WJ3 
    'xlWJ3FJ3'      , # WJ3FJ3 
    'xlWK1'      , # WK1 
    'xlWK1ALL'      , # WK1ALL 
    'xlWK1FMT'      , # WK1FMT 
    'xlWK3'      , # WK3 
    'xlWK3FM3'      , # WK3FM3 
    'xlWK4'      , # WK4 
    'xlWKS'      , # Worksheet 
    'xlWorkbookDefault'   , # Workbook default 
    'xlWorkbookNormal'    , # Workbook normal 
    'xlWorks2FarEast'    , # Works2 FarEast 
    'xlWQ1'      , # WQ1 
    'xlXMLSpreadsheet'    , # XML Spreadsheet 
    ] 

xl = win32com.client.gencache.EnsureDispatch("Excel.Application") 
'''if you use Dispatch('Excel.Application') without having run makepy first, 
    the constants from XlFileFormats will not be available. 
    See 
    http://docs.activestate.com/activepython/2.4/pywin32/html/com/win32com/HTML/GeneratedSupport.html 
    http://docs.activestate.com/activepython/2.4/pywin32/html/com/win32com/HTML/QuickStartClientCom.html 
    ''' 
app = xl.Application 
app.Visible = 1 
book = app.Workbooks.Add(); book.Activate() 
print 'DefaultSaveFormat:', app.DefaultSaveFormat 

# you cannot access the constants until AFTER you have dispatched excel 
constants = win32com.client.constants 

print 
app.DisplayAlerts = False 
for formatName in XlFileFormats: 
    formatNum = getattr(constants, formatName) 
    print '%-35s: %5d,' % (formatName, formatNum), 
    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"' % (wbext) 
     del wbname, wbext 
    #~ raw_input(' paused') 

app.Quit() 

這裏是輸出:

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 - Microsoft Excel」。所以我不確定這是怎麼回事。它看起來並不是一個非常有用的格式。