2012-11-15 2 views
3

파이썬과 pywin32를 사용하여 Excel 파일을 작성하는 응용 프로그램을 작성하려고하는데이 파일을 저장하는 데는 기본 형식과 확장명을 사용하여 사용자의 엑셀 버전을 저장해야합니다. 사용. Excel의 버전에 따라 기본 형식을 사용하는 경우 ".xlsx"확장명을 사용하는 "Open XML Workbook"이 될 수 있습니다. 다른 시간대에는 기본 엑셀 형식과 ".xls"확장자가 될 수 있습니다. 또한 사용자는 다른 기본 형식을 사용하도록 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

"임시 파일을 삭제하는 대신 이름을 변경하지 않는 이유는 무엇입니까?" - 엑셀이 파일을 잠그고 있기 때문에 엑셀이 열려있는 한 파일의 이름을 바꾸거나 삭제할 수 없기 때문입니다. – GarybCoder

답변

0

왜 xlfileformats의 DICT하지 : 확장 및 조회 할 것을 사용

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에서 가장 일반적인 형식을 포함 시켰습니다,하지만 당신은 그것을 살 수 있습니다 here과 같이 웹에있는 여러 출처에서 KeyError 예외 핸들러를 두지 않았지만 아마 하나를 원할 것입니다.

행운, 한 곳에서 열거 값과 확장을 포함하는 목록 이후 마이크

+0

확장 프로그램을 찾는 더 직접적인 방법을 찾고있었습니다. 그러나, 나는 이것이 임시 파일을 저장하는 것보다 깨끗하다고 ​​생각한다. 추신 제공 한 링크는 각 형식의 열거를 보여 주지만 확장을 제공하지는 않습니다. 나는 검색했고 두 표 모두를 찾기가 어렵다는 표를 보았다. 그것은 이상하다. 나는 그것을 밖으로 분류 할 것이다. 감사합니다 마이크 – 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"이 표시됩니다. 그래서 나는 이것으로 무슨 일이 일어나고 있는지 잘 모르겠습니다. 어쨌든 매우 유용한 형식처럼 보이지는 않습니다.

관련 문제