N. Chamaa N. Chamaa -4 years ago 340
Python Question

How to do coulmn alignment in openpyxl?

I am trying to align a column in openpyxl without success :

wb = Workbook()
ws = wb.active


....

ws.column_dimensions["A"].alignment = Alignment(horizontal='left')
ws.column_dimensions["C"].alignment = Alignment(horizontal='center')


The same for:

ws["A"].alignment = Alignment(horizontal='left')
ws["C"].alignment = Alignment(horizontal='center')


This isn't working for me.

Otherwise, iterating though cells and do alignement works correctly!!

Answer Source

You should have gotten the folling Traceback!
Please show us these if you post a Question!

ws["A"].alignment = Alignment(horizontal='left')
 AttributeError: 'tuple' object has no attribute 'alignment'

Styling a Range or even for whole column are not implemented. You have to do it by your own, for instance:

for row in rows:
    cell_A = row[:1][0]
    cell_A.alignment = Alignment(horizontal='left')  

Tested with Python:3.4.2 - openpyxl:2.4.1 - LibreOffice: 4.3.3.2

Come back and Flag your Question as answered or comment why not.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download