Python - Generate PDF from created Excel workbook - cannot save pdf document

0 votes

I'm attempting to convert an.xlsx workbook to a PDF file. I'm initially merging data from one spreadsheet into a new one (with some extra data conversion). I then save the new workbook to a temporary path. I then want to open the.xlsx file I just prepared and save it as a PDF.

But when I'm trying to save it, I get this message:

Błąd: (-2147352567, 'Wystąpił wyjątek.', (0, 'Microsoft Excel', 'Nie zapisano dokumentu. Być może jest on otwarty lub przy zapisywaniu napotkano błąd.', 'xlmain11.chm', 0, -2146827284), None)

(it is in Polish) The document was not saved. Perhaps it is open or an error was encountered when saving it

Without code, that is supposed to save a .pdf file, .xlsx file is created correctly.

Code of my program:

import sys
import openpyxl
from openpyxl import Workbook
from openpyxl.drawing.image import Image
from openpyxl.utils import get_column_letter
from tkinter.filedialog import asksaveasfile
import os
from win32com import client

initialFile = sys.argv[1]
initialCatalog = sys.argv[2]
assetsCatalog = f"{initialCatalog}\\api\\assets"

def codeToPictogram(code):
  for files in os.walk(assetsCatalog):
      if f'{code}.png' in files[2]:
          return 1
      else:
          return 0

try:
    wb = openpyxl.load_workbook(initialFile)
    ws = wb.active
    ws.title = "Stan techniczny nawierzchni"

    for row in ws.iter_cols(min_row=2, min_col=2, max_row=ws.max_row, max_col=ws.max_column):  
        for cell in row:  
            if(cell.value is None):
                continue
            if (codeToPictogram(cell.value) == 1):
                img = Image(f"{assetsCatalog}\\{cell.value}.png")
                img.height = 100
                img.width = 100
                ws.add_image(img, f"{get_column_letter(cell.column)}{cell.row}")
    file = asksaveasfile(defaultextension='.pdf',title = 'Zapisz stan techniczny', filetypes=[("Plik PDF", "*.pdf")])
    if file is not None:
        wb.save(f'{initialCatalog}\\api\\temp\\temp.xlsx')
        # wb.close()
        
        excel = client.Dispatch("Excel.Application")
        sheets = excel.Workbooks.Open(f'{initialCatalog}\\api\\temp\\temp.xlsx')
        work_sheets = sheets.Worksheets[0]
        work_sheets.ExportAsFixedFormat(0, file.name)
        
        print("Gotowe!")
        input("Wciśnij Enter, aby zamknąć...")
except Exception as e:
    print(f"Błąd: {e}")
    input("Wciśnij Enter, aby zamknąć...")

I attempted to use wb.close() but was unable. I searched through the openpyxl instructions, but I was unable to locate a method for first saving a new workbook as an.xlsx file before saving it as a.pdf.

As this is my first try at creating a Python application, there may be something quite trivial that I am unaware of. I'm attempting to switch from C#:)

Apr 6, 2023 in Others by Kithuzzz
• 38,000 points
999 views

1 answer to this question.

0 votes
The problem is that temp.xlsx doesn't shut off Excel. Excel is still open and has a lock on the file. Hence, the file is locked when you attempt to write to it.

I'm not sure how to solve this, but instead of storing to a temporary file for this use case, you may try pandas.
answered Apr 6, 2023 by narikkadan
• 63,600 points

Related Questions In Others

0 votes
1 answer

How to convert data from txt files to Excel files using python

Hi , there are few steps to ...READ MORE

answered Feb 16, 2022 in Others by Edureka
• 13,690 points
14,024 views
0 votes
1 answer

How can I convert excel to PDF by Libreoffice and keep all format from excel file?

"Times New Roman" typeface does not have ...READ MORE

answered Oct 3, 2022 in Others by narikkadan
• 63,600 points
1,648 views
0 votes
1 answer

Batch generate merged .jpg from excel data sheet

Refer to this blog and follow the ...READ MORE

answered Oct 10, 2022 in Others by narikkadan
• 63,600 points
423 views
0 votes
1 answer

Create Excel file and save as PDF.

Office 2013 still has the Interop library and ...READ MORE

answered Oct 11, 2022 in Others by narikkadan
• 63,600 points
1,386 views
0 votes
0 answers

How to save Excel sheets to PDF using Python

I have a multiple-sheet Excel spreadsheet. I ...READ MORE

Apr 10, 2023 in Others by Kithuzzz
• 38,000 points
6,025 views
0 votes
1 answer

ImportError: openpyxl is required for loading excel format files

Forget the PsychoPy complications for the time ...READ MORE

answered Oct 3, 2018 in Python by Priyaj
• 58,020 points
1,078 views
0 votes
2 answers
0 votes
1 answer
0 votes
1 answer

Print chosen worksheets in excel files to pdf in python

In the simplest form: import win32com.client o = win32com.client.Dispatch("Excel.Application") o.Visible ...READ MORE

answered Sep 24, 2022 in Others by narikkadan
• 63,600 points
3,562 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP