How can I align text in a cell to the top with openpyxl?
Asked Answered
N

4

5

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

Napery answered 10/4, 2014 at 11:27 Comment(1)
Where is your try? Please add your code here.Wisdom
N
3

Try this:

sheet["A1"].alignment.vertical = "top"
Neutral answered 10/4, 2014 at 11:57 Comment(1)
remember style objects are immutable and cannot be changed. Reassign the style with a copyEarful
A
7

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

Airframe answered 28/9, 2018 at 22:46 Comment(0)
N
3

Try this:

sheet["A1"].alignment.vertical = "top"
Neutral answered 10/4, 2014 at 11:57 Comment(1)
remember style objects are immutable and cannot be changed. Reassign the style with a copyEarful
B
1

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

Bolding answered 30/3, 2020 at 7:0 Comment(1)
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
L
0

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.

Lascivious answered 10/4, 2014 at 11:44 Comment(4)
This statement didn't seem to work for me, I don't know why, but the answer above did work. Thanks for your responseNapery
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 NoneFuzzy
AttributeError("Style objects are immutable and cannot be changed." AttributeError: Style objects are immutable and cannot be changed.Reassign the style with a copyCeylon

© 2022 - 2024 — McMap. All rights reserved.