Streak Streak - 2 years ago 558
Python Question

Horizontal text alignment in openpyxl

I'm tryign to change the text alignment to the center of 2 merged sells, I've found some answers that didn't work for my case

currentCell = ws.cell('A1') = 'center' #TypeError: cannot set horizontal attribute
#or = Alignment.HORIZONTAL_CENTER #AttributeError: type object 'Alignment' has no attribute 'HORIZONTAL_CENTER'

both didn't work, is there any other ways to do it?

Answer Source

You can achieve this by using Python XlsxWriter library.

import xlsxwriter

workbook = xlsxwriter.Workbook('example.xlsx')
worksheet = workbook.add_worksheet()

cell_format = workbook.add_format({'align': 'center'})

worksheet.merge_range('A1:B1', "")
worksheet.write_rich_string('A1','Example', cell_format)


Here i have merged cells A1, B1 and added a cell format parameter which includes the align parameter assigned as center.

enter image description here

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