2

i need to print an excel sheet and need to do it using some kind of python script. So far i have used win32com in my script and i also got it done to get a printout using the following code:

import win32com.client

o = win32com.client.Dispatch("Excel.Application")
o.Visible = 1
wb = o.Workbooks.Open(r'C:\test.xlsx')
ws = wb.Worksheets[1]
ws.PrintOut()

Unfortunately before i actually print the excel-sheet i need to adjust the print settings of this sheet/file: change format to landscape and change to small/narrow margin.

I have found this site that might contain just what i need: https://msdn.microsoft.com/en-us/library/aa220363(v=office.11).aspx

Unfortunately so far i have not been able to change the desired print properties. I hope someone can help me with this or at least get me headed into the right direction.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
H123321
  • 138
  • 2
  • 11

1 Answers1

3

You can edit the print settings using the PageSetup Method (https://learn.microsoft.com/en-us/previous-versions/office/developer/office-2003/aa173425%28v%3doffice.11%29). Does not seem to have a narrow/wide/normal margin setting as you normally see in the excel application, but you can specify the margins yourself.

ws.PageSetup.Zoom = False
ws.PageSetup.FitToPagesTall = 1
ws.PageSetup.FitToPagesWide = 1
ws.PageSetup.PrintArea = print_area
ws.PageSetup.LeftMargin = 25
ws.PageSetup.RightMargin = 25
ws.PageSetup.TopMargin = 50
ws.PageSetup.BottomMargin = 50
wb.ExportAsFixedFormat(0, path_to_pdf)

I am using ExportAsFixedFormat, but I guess this should work for PrintOut() too.

Reference: Print chosen worksheets in excel files to pdf in python

EDIT:

The FitToPagesTall (fits all rows on one page) and FitToPagesWide (fits all columns on one page) settings will mess up your eventual print area if you have them both set to True. You will need to specify at least one of them as False to see your margin settings take effect.

ws.PageSetup.FitToPagesTall = False
ws.PageSetup.FitToPagesWide = 1
xrt
  • 106
  • 2
  • 7