[Python] Saving Excel files as PDF using win32com python library and getting error

Discussão em 'Python' iniciado por Stack, Maio 29, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to run a script that reads a txt file that contains a list of file paths to Excel files, and save each one as a pdf in a specified directory. I can get it to read the txt file and parse the list of file paths no problem, but it runs into an error when it tries to save the file as a pdf.

    Here's my save pdfs function that runs into an error:

    def save_pdfs(files_list,export_folder):
    for line_item, filename in enumerate(files_list, start=1):
    excel = client.Dispatch("Excel.Application")
    excel.Application.DisplayAlerts = False
    print(line_item, f'{filename}')
    try:
    wb = excel.Workbooks.Open(filename, ReadOnly=True)
    work_sheets = wb.Worksheets[0]
    if len(str(line_item)) == 1:
    work_sheets.ExportAsFixedFormat(0, f'{export_folder}\\0{line_item}')
    else:
    work_sheets.ExportAsFixedFormat(0, f'{export_folder}\\{line_item}')
    except Exception as e:
    print(f"An error occurred: {e}")
    finally:
    wb.Close(False)
    excel.Application.DisplayAlerts = True
    excel.Quit()


    And whenever I run this, I get the following error for each of the files:

    An error occurred: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'Document not saved. The document may be open, or an error may have been encountered when saving.', 'xlmain11.chm', 0, -2146827284), None)


    I don't have Excel running when I start the script and I've checked the files themselves and nobody else has the file open already. If anyone else has run into a similar situation, please let me know what you did to fix it.

    Continue reading...

Compartilhe esta Página