Streak Streak - 6 months ago 89
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')
currentCell.style.alignment.horizontal = 'center' #TypeError: cannot set horizontal attribute
#or
currentCell.style.alignment.vertical = 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

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)

workbook.close()

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