2

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 alignment works correctly!

Cœur
  • 37,241
  • 25
  • 195
  • 267
N. Chamaa
  • 1,507
  • 3
  • 12
  • 22

2 Answers2

14

You should have gotten the failing Traceback!
Please show us this if you post a question!

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

Styling a Range or even a whole column is not implemented. You have to do it on 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

Ben
  • 5,952
  • 4
  • 33
  • 44
stovfl
  • 14,998
  • 7
  • 24
  • 51
6
from openpyxl import load_workbook
from openpyxl.styles import Alignment

xlsx_file = 'file.xlsx'

# openning:
wb = load_workbook(filename = xlsx_file)

# center align column H in the default sheet:
ws = wb.active
for row in ws[2:ws.max_row]:  # skip the header
    cell = row[7]             # column H
    cell.alignment = Alignment(horizontal='center')

# saving:
wb.save(xlsx_file)
Adobe
  • 12,967
  • 10
  • 85
  • 126