6

I have a main folder with some .xlsx, .ipynb, .jpeg and some subfolders in it. Now I want to convert all my .xlsx files in my main folder to PDFs.

It is a routine work that I have to do everyday, I would appreciate if you teach me how to do it in python.

*all the files have some data in the first sheet of the workbook

Thank you

2
  • 1
    seems helpful: stackoverflow.com/a/61587091/8485707 Commented Mar 1, 2021 at 12:20
  • unfortunately wkhtmltopdf is not available for python3. Commented Mar 2, 2021 at 13:36

2 Answers 2

9

Is there anything you have already tried ?

I suggest testing out pywin32.

  1. Download pywin32
python3 -m pip install pywin32
  1. Write a script to automate.
import win32com.client
from pywintypes import com_error

# Path to original excel file
WB_PATH = r'~/path/to/file.xlsx'
# PDF path when saving
PATH_TO_PDF = r'~/path/to/file.pdf'
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = False
try:
    print('Start conversion to PDF')
    # Open
    wb = excel.Workbooks.Open(WB_PATH)
    # Specify the sheet you want to save by index. 1 is the first (leftmost) sheet.
    ws_index_list = [1,2,3,4,5,6,7,8,9,10,11,12]
    wb.WorkSheets(ws_index_list).Select()
    # Save
    wb.ActiveSheet.ExportAsFixedFormat(0, PATH_TO_PDF)
except com_error as e:
    print('failed.')
else:
    print('Succeeded.')
finally:
    wb.Close()
    excel.Quit()
Sign up to request clarification or add additional context in comments.

5 Comments

yes I saw this script when I was googling, but couldn’t get from here to multiple excels in one folder
Didn't get past Dispatch: pywintypes.com_error: (-2147023728, 'Element not found.', None, None) using Conda Python 3.8.3 and pywin32 v227
Hi @xtian you have to have excel installed as it essentially opens excel and automates the process of exporting it to pdf. For checking what the error code -2147023728 means this answer seems helpful.
Hi @sam_sam can you explain in detail what issues you are facing ? Are you getting any errors or is it just not providing the result you were hoping for. Sorry for the extremely late reply, it's been a while since I opened stackoverflow.
My server runs on linux, is there any alternative to this?
-7

try like this :

saveFormat = self.SaveFormat

workbook = self.Workbook(self.dataDir + "Book1.xls")

#Save the document in PDF format

workbook.save(self.dataDir + "OutBook1.pdf", saveFormat.PDF)

\# Print message

print "\n Excel to PDF conversion performed successfully."

2 Comments

what is that “.self “ it gives me this error "NameError: name 'self' is not defined"
This code stems from a class. That's why the "self" appears. The code should be revised by the author.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.