Is there any way to keep borders of the data cells from Pandas Style when saving dataframe to Excel?

Question:

With .style.set_table_styles I can add borders to my df but when I write the df to excel file I see that it only keeps borders for header and index part. Borders of the data cells are disappearing. Here is the example code;

df1 = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6]})

df1.style.set_table_styles([
    {"selector": "", "props": [("border", "1px solid black")]},
    {'selector': 'tbody td','props': [('border', '1px solid black')]},
    {"selector": "th", "props": [("border", "1px solid black")]}
                           ]
                           , axis=1, overwrite=False)
df1.to_excel('df.xlsx')

Am I missing something or this is not manageable with pandas.style?

Asked By: Baran Aldemir

||

Answers:

This works for me, but it doesn’t use style, do you absolutely want it ? :

import pandas as pd
import xlsxwriter

df1 = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6]})
writer = pd.ExcelWriter('df.xlsx', engine='xlsxwriter')
df1.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(df1), len(df1.columns)), {'type': 'no_errors', 'format': border_fmt})
writer.save()
writer.close()
Answered By: grymlin

I think I found my answer with Styler.set_properties

df1 = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6]})

df1 = df1.style.set_properties(**{'border-color': 'black', 'border-width': '1px', 'border-style': 'solid'})
df1.to_excel('df.xlsx')
Answered By: Baran Aldemir
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.