I want the text in an Excel cell to align with the top, rather then with the bottom, when writing a file from python using openpyxl
How can I align text in a cell to the top with openpyxl?
Where is your try? Please add your code here. –
Wisdom
Try this:
sheet["A1"].alignment.vertical = "top"
remember style objects are immutable and cannot be changed. Reassign the style with a copy –
Earful
This works for me. I am using openpyxl v2.5.8.
new_cell.alignment=Alignment(horizontal='general',
vertical='top',
text_rotation=0,
wrap_text=False,
shrink_to_fit=False,
indent=0)
For more info: https://openpyxl.readthedocs.io/en/stable/styles.html?highlight=cell%20alignment
Try this:
sheet["A1"].alignment.vertical = "top"
remember style objects are immutable and cannot be changed. Reassign the style with a copy –
Earful
Use two loops to apply the alignment format to each cell.
al = Alignment(horizontal="left", vertical="top")
for row in sheet['A1':'A2']:
for cell in row:
cell.alignment = al
This idea comes from https://groups.google.com/forum/#!topic/openpyxl-users/GDrfknwrYEM
Hi, this answer was in the low-quality review queue. Code-only answers may solve the question but they are much more useful if you explain why they are correct. The community benefits from theory as well as code to understand your answer fully. –
Schorl
You set the cell style.alignment.vertical
to a desired value. For example, to make the cell A1
to vertically align up:
# ws is worksheet
myCell = ws.cell('A1')
myCell.style.alignment.vertical = Alignment.VERTICAL_TOP
Find more details on the class reference page here.
This statement didn't seem to work for me, I don't know why, but the answer above did work. Thanks for your response –
Napery
No problem. Maybe you ignored the comment saying that ws is a worksheet. But the important thing is you got it working. –
Lascivious
also currentCell is None –
Fuzzy
AttributeError("Style objects are immutable and cannot be changed." AttributeError: Style objects are immutable and cannot be changed.Reassign the style with a copy –
Ceylon
© 2022 - 2024 — McMap. All rights reserved.