How can I center align in pandas dataframe only cell that i want

writer=pd.ExcelWriter('Data.xlsx',engine='openpyxl')
emptydf.to_excel(writer,sheet_name=('Sheet1'),na_rep='-')
concat5.to_excel(writer,sheet_name=('Sheet2'),na_rep='-')
workbook=writer.book
writer.save()

enter image description here

What I want is align to center only cells that "-". It is aligned to left right now. I want to know how i could this. Thank you.

1 answer

  • answered 2020-06-02 11:38 0buz

    This is an openpyxl solution:

    from openpyxl.styles import Alignment
    from openpyxl import load_workbook
    
    wb = load_workbook('Data.xlsx')
    ws_names=wb.get_sheet_names()
    
    for ws_name in ws_names:
        for row_cells in wb.get_sheet_by_name(ws_name):
            for cell in row_cells:
                if cell.value == '-':
                    cell.alignment = Alignment(horizontal='center')
    
    wb.save('Data.xlsx')
    wb.close()