3

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

sam_sam
  • 449
  • 1
  • 5
  • 16

2 Answers2

6

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()
Thisas
  • 63
  • 9
  • yes I saw this script when I was googling, but couldn’t get from here to multiple excels in one folder – sam_sam Mar 02 '21 at 13:38
  • Didn't get past Dispatch: `pywintypes.com_error: (-2147023728, 'Element not found.', None, None)` using Conda Python 3.8.3 and pywin32 v227 – xtian Sep 26 '21 at 01:56
  • 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](https://stackoverflow.com/a/24326638/13249661) seems helpful. – Thisas Jun 30 '22 at 11:59
  • 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. – Thisas Jun 30 '22 at 12:01
-5

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."
Salma Elshahawy
  • 1,112
  • 2
  • 11
  • 21
Ryuzen
  • 1