如何使用 python 中的样式突出显示 excel 中的 header?
How to highlight header in excel using styles in python?
我有一个看起来像这样的数据框。
ID
Name
Sales
Sales2
111
SAM
xxx
xxx
123
JON
xxx
xxx
我想制作一个这样的excel。
我尝试使用设置表,但它不起作用
styles = [{ 'props': ('background-color: green') }]
fd_final_highlight = fd_final.style.set_table_styles(styles)
Weekly_excel= pd.ExcelWriter('C:/Users/xxx.....xlsx', engine='xlsxwriter')
fd_final_highlight.to_excel(Weekly_excel, sheet_name='Master', index=0)
Weekly_excel.save()
可能的解决方案如下:
import pandas as pd
data = {"col1": [1, 2, 3], "col2": [1, 2, 3]}
df = pd.DataFrame.from_dict(data)
writer = pd.ExcelWriter('C:/Users/xxx.....xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Master', startrow=1, header=False, index=False)
workbook = writer.book
worksheet = writer.sheets['Master']
# Set a header format
header_format = workbook.add_format({'bold': True, 'fg_color': 'green'})
for col_num, value in enumerate(df.columns.values):
worksheet.write(0, col_num, value, header_format)
writer.save()
这是答案:
df.style.set_table_styles(
[{'selector': 'th.col_heading',
'props': [('background-color', 'yellow')]}])
In your code
styles = [{'selector': 'th.col_heading',
'props': [('background-color', 'yellow')]}]
fd_final.style.set_table_styles(styles)
fd_final.to_excel(<your_path>, sheet_name='Master', index=0)
我有一个看起来像这样的数据框。
ID | Name | Sales | Sales2 |
---|---|---|---|
111 | SAM | xxx | xxx |
123 | JON | xxx | xxx |
我想制作一个这样的excel。
我尝试使用设置表,但它不起作用
styles = [{ 'props': ('background-color: green') }]
fd_final_highlight = fd_final.style.set_table_styles(styles)
Weekly_excel= pd.ExcelWriter('C:/Users/xxx.....xlsx', engine='xlsxwriter')
fd_final_highlight.to_excel(Weekly_excel, sheet_name='Master', index=0)
Weekly_excel.save()
可能的解决方案如下:
import pandas as pd
data = {"col1": [1, 2, 3], "col2": [1, 2, 3]}
df = pd.DataFrame.from_dict(data)
writer = pd.ExcelWriter('C:/Users/xxx.....xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Master', startrow=1, header=False, index=False)
workbook = writer.book
worksheet = writer.sheets['Master']
# Set a header format
header_format = workbook.add_format({'bold': True, 'fg_color': 'green'})
for col_num, value in enumerate(df.columns.values):
worksheet.write(0, col_num, value, header_format)
writer.save()
这是答案:
df.style.set_table_styles(
[{'selector': 'th.col_heading',
'props': [('background-color', 'yellow')]}])
In your code
styles = [{'selector': 'th.col_heading',
'props': [('background-color', 'yellow')]}]
fd_final.style.set_table_styles(styles)
fd_final.to_excel(<your_path>, sheet_name='Master', index=0)