user1681102
user1681102

Reputation: 193

How to add borders to a table in excel sheet created by pandas dataframe?

import pandas as pd
table =[[1,2,3,4],[11,12,13,14],["Pass","Fail","Pass","Fail"]]
df = pd.DataFrame(table)
df = df.transpose()
headers=["Current_Value","Previous_Value","Result",]
df.columns =headers

writer = pd.ExcelWriter("pandas.xlsx")

df.to_excel(writer, sheet_name='Sheet1')
writer.save()

This code will create a table with headers in bold. I want to add borders to the table that is present in the excel sheet. Will that be possible?

Upvotes: 7

Views: 13978

Answers (2)

Benson Mathew
Benson Mathew

Reputation: 155

For the above solution, I found out that the column width to be too small, to adjust that add sf.set_column_width('column name', column_width) before st.to_excel(...) So it will be:

sf.set_column_width('Current_Value', 50)
sf.to_excel(writer, sheet_name='Sheet1')
writer.save()

Upvotes: 0

You can use StyleFrame to add Borders/Colors to your Dataframe in Excel.

import pandas as pd
from StyleFrame import StyleFrame, Styler, utils

table =[[1,2,3,4],[11,12,13,14],["Pass","Fail","Pass","Fail"]]
df = pd.DataFrame(table)
df = df.transpose()
headers=["Current_Value","Previous_Value","Result",]
df.columns =headers

writer = StyleFrame.ExcelWriter("pandas.xlsx")

sf=StyleFrame(df)

sf.apply_column_style(cols_to_style=df.columns, styler_obj=Styler(bg_color=utils.colors.white, bold=True, font=utils.fonts.arial,font_size=8),style_header=True)

sf.apply_headers_style(styler_obj=Styler(bg_color=utils.colors.blue, bold=True, font_size=8, font_color=utils.colors.white,number_format=utils.number_formats.general, protection=False))

sf.to_excel(writer, sheet_name='Sheet1')
writer.save()

Upvotes: 5

Related Questions