Search code examples
pythonopenpyxlxlsx

How to write text in a cell from top to bottom in openpyxl


I'd like to write text in a cell from top to bottom just like the vertical text orientation in EXCEL using openpyxl packages in python. But I can't do that. Could anyone please help me? I uploaded the exact image I want


Solution

  • Use the alignment attribute of a cell and set the textRotation to the needed angle (1-180). You can read more abot it in the openpyxl documentation - Here.

    Code Example:

    from openpyxl import Workbook
    from openpyxl.styles import Alignment
    
    wb = Workbook()
    ws = wb.active
    
    ws['A1'] = 'Example'
    ws['A1'].alignment = Alignment(textRotation=180)
    
    wb.save('Example.xlsx')
    

    Output:

    rotated text in Excel

    If you want the charecters to be written horizontally but the word verticaly just set textRotation to 255:

    from openpyxl import Workbook
    from openpyxl.styles import Alignment
    
    wb = Workbook()
    ws = wb.active
    
    ws['A1'] = 'Hello'
    ws['A1'].alignment = Alignment(textRotation=255)
    
    wb.save('Example.xlsx')
    

    Output:

    Text Rotation 2