.xlsx和xls(最新版本)到pdf使用python [英] .xlsx and xls(Latest Versions) to pdf using python

查看:412
本文介绍了.xlsx和xls(最新版本)到pdf使用python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

借助此 .doc to pdf使用python
链接我正在尝试excel(.xlsx和xls格式)

With the help of this .doc to pdf using python Link I am trying for excel (.xlsx and xls formats)

以下是修改的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)
>>>

doc.SaveAs(out_file,FileFormat = 56)

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

What should be FileFormat file format? Please Help

推荐答案

xlsxwriter的链接:

Link of xlsxwriter :

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

有了这个帮助,您可以使用 .xlsx .xls

With the help of this you can generate excel file with .xlsx and .xls

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

for example excel file generated name is 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')

这篇关于.xlsx和xls(最新版本)到pdf使用python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆