Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the pages in a Worksheet to apply the openpyxl page module

I am trying to format the page margins of a template file that I load in via openpyxl. I'm trying to use from openpyxl.worksheet.page.PageMargins but I get the error AttributeError: 'Worksheet' object has no attribute 'PageMargins'.

A sample of the code is below:

from openpyxl import load_workbook
from openpyxl.worksheet.page import PageMargins
wb = load_workbook('example.xlsx')
ws_example = wb['Sheet1']
ws_example.PageMargins(left=0.5, right=0.4, top=0.612, bottom=0.1, header=0.2, footer=0.3)

It makes sense that applying the page module function to an entire worksheet would get an error but I don't understand how to access the seperate pages. The 'Sheet1' in this case is a 2 page sheet with some headers/footers that is planned to be printed out.

I tried for page in ws_example to apply PageMargins but each page is tuple. I have 3.0.9 openpyxl.

like image 705
cloudyweather Avatar asked Nov 20 '25 19:11

cloudyweather


1 Answers

I think you need to assign the returned PageMargins object to the page_margins property of your sheet

ws_example.page_margins = PageMargins(left=0.5, right=0.4, top=0.612, bottom=0.1, header=0.2, footer=0.3)
like image 111
wstk Avatar answered Nov 23 '25 08:11

wstk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!