python - .xlsx 和 xls(最新版本)使用 python 到 pdf

标签 python excel pdf excel-2010 win32com

借助这个.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)
>>>

有问题

doc.SaveAs(out_file, FileFormat=56)

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

最佳答案

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 - .xlsx 和 xls(最新版本)使用 python 到 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20854840/

相关文章:

python - 将 pandas 多重索引转换为日期时间格式

python - 浮点值作为字典键

Python - 错误 : couldn't open . png 文件

php - Virtuemart 2 pdf 生成

xml - PDF导出在Grails 2.3.2中不起作用

python - 在 Linux 中,如何从命令行获取我正在使用的 Python 二进制文件的绝对路径?

excel - 运行时错误 50012 - 对象 "Export"的方法 'VBComponent' 失败错误

excel - 如何在 SUMPRODUCT() 中获取 FORMULATEXT() 的长度?

excel - 如何在 Excel 中跨列处理多个 IFTHEN 查询?

javascript - 从 AJAX 下载 PDF 文件成功回调