Horizontal text alignment in openpyxl

后端 未结 4 1394
迷失自我
迷失自我 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:07

    None of the other solutions worked for me, since my solution requires openpyxl, and at least in 2.1.5 cell.alignment can't be set directly.

    from openpyxl.styles import Style, Alignment
    
    cell = ws.cell('A1')
    cell.style = cell.style.copy(alignment=Alignment(horizontal='center')) 
    

    The above copies the current style and replaces the alignment. You can also create a whole new style - with any values not specified taking the default values from https://openpyxl.readthedocs.org/en/latest/styles.html

    cell.style = Style(alignment=Alignment(horizontal='center'),font=Font(bold=True))
    
    # or - a tidier way
    
    vals = {'alignment':Alignment(horizontal='center'),
            'font':Font(bold=True),
           }
    new_style = Style(**vals)
    cell.style = new_style
    

提交回复
热议问题