How center text horizontally using Alignment in OpenPyXL
Based on our previous OpenPyXL minimal XLSX write example, this code will generate a XLSX with a number in cellĀ A1
that is right-aligned automatically:
from openpyxl import Workbook
wb = Workbook()
sheet = wb["Sheet"] # This sheet is created by default
# Add content to sheet
sheet["A1"] = 4.5
sheet["A1"].alignment = Alignment(horizontal="center")
# Save
wb.save("openpyxl-test.xlsx")
How to add centered alignment
In order to align the cell horizontally, we just need to
from openpyxl.styles.alignment import Alignment
sheet["A1"].alignment = Alignment(horizontal="center")
Full example
from openpyxl import Workbook
from openpyxl.styles.alignment import Alignment
wb = Workbook()
sheet = wb["Sheet"] # This sheet is created by default
# Add content to sheet
sheet["A1"] = 4.5
sheet["A1"].alignment = Alignment(horizontal="center")
# Save
wb.save("openpyxl-test.xlsx")
This will look like this: