Search code examples
pythonpandaspandas.excelwriter

Python ExcelWriter formatting 'all borders'


I have this enter image description here

I want this

enter image description here

I look at the docs but I cannot see a function that would achieve this.


Solution

  • You can add a format to columns with something like this (you will have to play with the styles to get the thickness you want):

    import pandas as pd
    import numpy as np
    import xlsxwriter
    
    df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns=['a', 'b', 'c'])
    writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
    df.to_excel(writer, sheet_name='Sheet1')
    workbook = writer.book
    worksheet = writer.sheets['Sheet1']
    
    border_fmt = workbook.add_format({'bottom':5, 'top':5, 'left':5, 'right':5})
    worksheet.conditional_format(xlsxwriter.utility.xl_range(0, 0, len(df), len(df.columns)), {'type': 'no_errors', 'format': border_fmt})
    writer.save()
    

    And here is a link to the format examples: https://xlsxwriter.readthedocs.io/format.html