使用python将.xlsx和xls(最新版本)转换为pdf

2024-09-21 00:18:30 发布

您现在位置:Python中文网/ 问答频道 /正文

借助这个.doc to pdf using python 链接我正在尝试excel(.xlsx和xls格式)

以下是Excel的修改代码:

import os
from win32com import client

folder = "C:\\Oprance\\Excel\\XlsxWriter-0.5.1"
file_type = 'xlsx'
out_folder = folder + "\\PDF_excel"

os.chdir(folder)

if not os.path.exists(out_folder):
    print 'Creating output folder...'
    os.makedirs(out_folder)
    print out_folder, 'created.'
else:
    print out_folder, 'already exists.\n'

for files in os.listdir("."):
    if files.endswith(".xlsx"):
        print files

print '\n\n'

word = client.DispatchEx("Excel.Application")
for files in os.listdir("."):
    if files.endswith(".xlsx") or files.endswith('xls'):
        out_name = files.replace(file_type, r"pdf")
        in_file = os.path.abspath(folder + "\\" + files)
        out_file = os.path.abspath(out_folder + "\\" + out_name)
        doc = word.Workbooks.Open(in_file)
        print 'Exporting', out_file
        doc.SaveAs(out_file, FileFormat=56)
        doc.Close()

显示以下错误:

>>> execfile('excel_to_pdf.py')
Creating output folder...
C:\Excel\XlsxWriter-0.5.1\PDF_excel created.
apms_trial.xlsx
~$apms_trial.xlsx

Exporting C:\Excel\XlsxWriter-0.5.1\PDF_excel\apms_trial.pdf
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "excel_to_pdf.py", line 30, in <module>
    doc = word.Workbooks.Open(in_file)
  File "<COMObject <unknown>>", line 8, in Open
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel
', u"Excel cannot open the file '~$apms_trial.xlsx' because the file format or f
ile extension is not valid. Verify that the file has not been corrupted and that
 the file extension matches the format of the file.", u'xlmain11.chm', 0, -21468
27284), None)
>>>

里面有问题

文档另存为(out_file,FileFormat=56)

文件格式应该是什么? 请帮忙


Tags: theindocpdfosfilesfolderout
3条回答

xlsxwriter链接:

https://xlsxwriter.readthedocs.org/en/latest/contents.html

借助此功能,您可以使用.xlsx.xls生成excel文件

例如,excel文件生成的名称是trial.xls

如果要生成该excel文件的pdf,请执行以下操作:

from win32com import client
xlApp = client.Dispatch("Excel.Application")
books = xlApp.Workbooks.Open('C:\\excel\\trial.xls')
ws = books.Worksheets[0]
ws.Visible = 1
ws.ExportAsFixedFormat(0, 'C:\\excel\\trial.pdf')

您可以使用python在linux上将excel工作表打印为pdf格式。 确实需要将openoffice作为无头服务器运行并使用unoconv,需要进行一些配置,但是是可行的

将OO作为(服务)守护进程运行,并将其用于xls、xlsx和doc、docx的转换。

http://dag.wiee.rs/home-made/unoconv/

我得到了同样的东西和同样的错误。。。答:57。。。。见下文。。。

from win32com import client
import win32api

def exceltopdf(doc):
    excel = client.DispatchEx("Excel.Application")
    excel.Visible = 0

    wb = excel.Workbooks.Open(doc)
    ws = wb.Worksheets[1]

    try:
        wb.SaveAs('c:\\targetfolder\\result.pdf', FileFormat=57)
    except Exception, e:
        print "Failed to convert"
        print str(e)
    finally:
        wb.Close()
        excel.Quit()

。。。作为脆弱的ExportAsFixedFormat的替代。。。

相关问题 更多 >

    热门问题