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()
此代码将创建一个包含粗体标题的表格。我想为excel表中存在的表添加边框。那可能吗?
答案 0 :(得分:2)
您可以使用StyleFrame将边框/颜色添加到Excel中的Dataframe。
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()
答案 1 :(得分:0)
对于上述解决方案,我发现列宽太小,无法进行调整以在st.to_excel(...)之前添加sf.set_column_width('column name',column_width)。 它将是:
sf.set_column_width('Current_Value', 50)
sf.to_excel(writer, sheet_name='Sheet1')
writer.save()