简体   繁体   English

将多个excel文件转换成python中的PDF文件

[英]Convert multiple excel files into PDF files in python

The win32com package works fine on a single excel file when converting it into a pdf. win32com package 在将单个 excel 文件转换为 pdf 时可以正常工作。 But when I run it in a loop to convert multiple excel files, it fails and gives an error message.但是当我在循环中运行它来转换多个 excel 文件时,它会失败并给出错误消息。 (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146777998), None)

For single File:-对于单个文件:-

from win32com import client

input_file =r"...\input.xlsx"
output_file = r"...\ouput.pdf"
excel  = client.DispatchEx("Excel.Application")
excel.Interactive = False
excel.Visible = False
Workbook = excel.Workbooks.Open(input_file,None, True)
try:
    Workbook.ActiveSheet.ExportAsFixedFormat(0, output_file)
    print("PDF Created successfully!!")
except Exception as e:
    print("Failed, try again")
    print(str(e))

For multiple files:-对于多个文件:-

from win32com import client
import os

directory = "...directory path"
path = os.path.join(directory)
for f in os.listdir(directory):
    file_name, file_extension = os.path.splitext(f) #split file name and extention
    inputFilePath = directory+ "/" + f
    outputFilePath = file_name + '.pdf'
    if file_extension == '.xlsx':
        excel  = client.DispatchEx("Excel.Application")
        excel.Interactive = False
        excel.Visible = False
        Workbook = excel.Workbooks.Open(inputFilePath , None, True)
        try:
            Workbook.ActiveSheet.ExportAsFixedFormat(0, outputFilePath)
            print("processing..")
        except Exception as e:
            print("Failed, try again")

I would appreciate any suggestions you can make.我将不胜感激您提出的任何建议。 Thanks!!谢谢!!

I know that this solution might be too late for you.我知道这个解决方案对你来说可能为时已晚。 I think your problem comes from inputfilepath and outputfilepath variables.我认为您的问题来自 inputfilepath 和 outputfilepath 变量。 I've tweaked your code and is working.我已经调整了你的代码并且正在工作。

` `

from win32com import client
import os

directory = r"....directory path...."
for file in os.listdir(directory):
    file_name, file_extension = os.path.splitext(file)  # split file name and extension
    input_file_path = os.path.join(directory, file)
    output_file_path = os.path.join(directory, file_name + '.pdf')
    if file_extension == '.xlsx' or file_extension == '.xls':
        excel = client.DispatchEx("Excel.Application")
        excel.Interactive = False
        excel.Visible = False
        workbook = excel.Workbooks.Open(input_file_path, None, True)
        workbook.ActiveSheet.ExportAsFixedFormat(0, output_file_path)

` `

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM