Horizontal text alignment in openpyxl

后端 未结 4 1389
迷失自我
迷失自我 2021-02-07 05:48

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\')
cu         


        
4条回答
  •  [愿得一人]
    2021-02-07 06:24

    This is what finally worked for me with the latest version from PIP (2.2.5)

        # center all cells
        for col in w_sheet.columns:
            for cell in col:
                # openpyxl styles aren't mutable,
                # so you have to create a copy of the style, modify the copy, then set it back
                alignment_obj = cell.alignment.copy(horizontal='center', vertical='center')
                cell.alignment = alignment_obj
    

    Update:

    As of openpyxl version 2.4.0 (~2016) the .copy() method is deprecated for StyleProxy objects.

    Try changing the last two lines to:

    from copy import copy
    alignment_obj = copy(cell.alignment)
    alignment_obj.horizontal = 'center'
    alignment_obj.vertical = 'center'
    cell.alignment = alignment_obj
    

提交回复
热议问题