Python convert (read & save) excel xlsx to xls

前端 未结 3 1768
独厮守ぢ
独厮守ぢ 2021-01-14 03:18

How can I convert an existing xlsx Excel file into xls while retaining my Excel file formatting? I use Anaconda Python 3, so I\'m not sure I can us

3条回答
  •  我在风中等你
    2021-01-14 03:24

    Another solution would be to use subprocess to run Excel via powershell. This has the advantage of not using Windows-specific libraries so can work on WSL as well.

    import subprocess
    import textwrap
    import os
    
    xlsx = 'data.xlsx'
    ps = 'script.ps1'
    
    with open(ps, 'w') as f:
        f.write(textwrap.dedent('''\
            param ($File)
            $myDir = split-path -parent $MyInvocation.MyCommand.Path
            $excelFile = "$myDir\\" + $File
            $Excel = New-Object -ComObject Excel.Application
            $wb = $Excel.Workbooks.Open($excelFile)
            $out = "$myDir\\" + (Get-Item ("$myDir\\" + $File) ).Basename + ".xls"
            $wb.SaveAs($out, 56)
            $Excel.Quit()        
        '''))
    p = subprocess.Popen(["powershell.exe", '.\\'+ps, xlsx])
    p.communicate()
    os.remove(ps)
    

提交回复
热议问题