0

I have an xlsx file which is a template for a receipt. It contains images and cells. I used to go into the file manually, update the information and then export to pdf before sending to my clients. I would like to be able to convert an xlsx to pdf through python if possible.

My problem is no one shows a tutorial which just chooses a xlsx file and changes it to pdf. Or no decent video tutorial.

I've tried getting openpyxl to save it as an extension with .pdf but i know that was a long shot. And i tried to follow an example on stack overflow but it didnt work that well.

I keep getting :

File "<COMObject <unknown>>", line 5, in ExportAsFixedFormat 
Objects of type 'WindowsPath' can not be converted to a COM VARIANT

and I'm pretty stuck.

#this file will open a wb and save it as another file name
#this first part opens a file from a location and makes a copy to another location

from pathlib import Path
from win32com import client

#sets filename and file
file_name = 'After Summer Bookings.xlsx'
dir_path = Path('C:/Users/BOTTL/Desktop/Business')
new_file_name = 'hello.pdf'
new_save_place = Path('C:/Users/BOTTL/Desktop/Business Python')

xlApp = client.Dispatch("Excel.Application")
books = xlApp.Workbooks.Open(dir_path / file_name)
ws = books.Worksheets[0]
ws.Visible = 1
ws.ExportAsFixedFormat(0, new_save_place / new_file_name)

I'd like it to open the xlsx file I have called After Summer Bookings.xlsx and save it as a pdf file called hello.pdf

stovfl
  • 14,998
  • 7
  • 24
  • 51
James Novis
  • 343
  • 5
  • 15
  • 1
    "An example on SO" --> where's the link to what you tried to follow? https://stackoverflow.com/help/how-to-ask – tehhowch Mar 28 '19 at 13:29
  • Check this [thread](https://stackoverflow.com/questions/20854840/xlsx-and-xlslatest-versions-to-pdf-using-python). The path argument of `ExportAsFixedFormat` should match this format: `ExportAsFixedFormat(0, 'C:\\excel\\trial.pdf')` – glhr Mar 28 '19 at 13:34
  • Hi that's the thread I followed and the variables within my code are equal to what is above. – James Novis Mar 28 '19 at 13:48
  • the code works if instead of putting a path i just put the filename (hello.pdf) . It saves it to the C:\Users\BOTTL\Documents\ folder – James Novis Mar 28 '19 at 14:13

1 Answers1

1

Solved it myself :)

from pathlib import Path
from win32com import client

#sets filename and file
file_name = 'After Summer Bookings.xlsx'
dir_path = Path('C:/Users/BOTTL/Desktop/Business')
new_file_name = 'hello.pdf'
new_save_place = ('C:/Users/BOTTL/Desktop/Business Python/')
path_and_place = new_save_place + new_file_name

xlApp = client.Dispatch("Excel.Application")
books = xlApp.Workbooks.Open(dir_path / file_name)
ws = books.Worksheets[0]
ws.Visible = 1
ws.ExportAsFixedFormat(0,path_and_place)

when concatenating the location and the filename it didn't like that I had made it a path, so now that I removed path, it works like a dream :)

James Novis
  • 343
  • 5
  • 15