Home > OS >  determine number of pages in an Excel sheet
determine number of pages in an Excel sheet

Time:09-17

In python am trying to figure out the number of pages of an excel sheet before converting it to a PDF. i.e. if the excel sheet takes up 1 page, only print 1 page. If the document is 3 pages, print 3 pages. Does anybody know how I would go about counting the pages of the Excel document? Particularly if the row height is changed so that rows 1-29 are on 1 page but if another XLS file has rows 1-37 on the first page. Below is my code and what each line does. Writing the proper conditions is where the help is needed.

from win32com import client # Imports Module

excel = client.Dispatch("Excel.Application") # Opens Microsoft Excel
sheets = excel.Workbooks.Open(file path.XLS) # Reads Excel File
work_sheets = sheets.Worksheets[0] # Reads sheet 1 of the workbook
work_sheets.PageSetup.FitToPagesWide = 1 # makes it 1 page wide

if worksheet is num pages pages:
    work_sheets.PageSetup.FitToPagesTall = num pages # need to figure out how to measure it
    
work_sheets.ExportAsFixedFormat(0, file_path.pdf) # Convert into PDF File, (0 = pdf, 1 = xps), path and name

CodePudding user response:

I've found this piece of code on the internet, which looks logical:

(ActiveSheet.HPageBreaks.Count   1) * (ActiveSheet.VPageBreaks.Count   1)

HPageBreaks are the horizontal page breaks.
VPageBreaks are the vertical page breaks.

The number of pages always equals the number of breaks plus one.
As your sheet might be split, not only in horizontal, but also in vertical page breaks, this formula make sense.

CodePudding user response:

from win32com import client # Imports Module

excel = client.Dispatch("Excel.Application") # Opens Microsoft Excel
sheets = excel.Workbooks.Open(file path.XLS) # Reads Excel File
work_sheets = sheets.Worksheets[0] # Reads sheet 1 of the workbook
work_sheets.PageSetup.Zoom = False #compresses all pages work_sheets.PageSetup.FitToPagesWide = 1 # makes it 1 page wide 
work_sheets.PageSetup.FitToPagesTall = False #uses the correct number of pages
work_sheets.ExportAsFixedFormat(0, file_path.pdf) # Convert into (0 = pdf, 1 = xps), path and name
sheets = excel.Workbooks.Close() # closes XLS file
  • Related