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

 五洋顽石_449 发布于 2023-02-07 13:11

借助这个.doc到pdf使用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 "", line 1, in 
  File "excel_to_pdf.py", line 30, in 
    doc = word.Workbooks.Open(in_file)
  File ">", 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文件格式应该是什么?请帮忙

1 个回答
  • 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')
    

    2023-02-07 13:13 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有