[英]Fill colours using conditional formatting
我有一個熊貓數據框,如下所示:
import io
df = pd.read_table(io.StringIO('''\
A B C
SDF 899501607.2 -26152567.7
ISB 464284188.7 -20278910.23
我想使用pd.ExcelWriter將黃色填充到標題A,將紅色填充到標題B,將藍色填充到標題C。 我嘗試在下面的代碼中為列A填充黃色,但它用黃色填充標題的值,而不是僅填充標題(單元格A1)
writer = pd.ExcelWriter("output_file_name.xlsx", engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']
yellow_format = workbook.add_format({'bg_color':'yellow'})
l = ['A1:A1']
for columns in l:
worksheet.set_column(columns, 25, yellow_format)
xlsxwriter
旨在創建Excel文件,但無法讀取它們。 寫入后,它也無法格式化特定的單元格。
但是您可以使用這兩種方法之一來僅格式化標題。
使用conditional_format
(最快):
yellow_format = workbook.add_format({'bg_color': 'yellow'})
red_format = workbook.add_format({'bg_color': 'red'})
blue_format = workbook.add_format({'bg_color': 'blue'})
worksheet.conditional_format("A1", {'type': 'no_blanks', 'format': yellow_format})
worksheet.conditional_format("B1", {'type': 'no_blanks', 'format': red_format})
worksheet.conditional_format("C1", {'type': 'no_blanks', 'format': blue_format})
使用set_column
和set_row
的組合(慢,如果要為每行設置白色):
yellow_format = workbook.add_format({'bg_color': 'yellow'})
red_format = workbook.add_format({'bg_color': 'red'})
blue_format = workbook.add_format({'bg_color': 'blue'})
white_format = workbook.add_format({'bg_color': 'white'})
worksheet.set_column(first_col=0, last_col=0, cell_format=yellow_format)
worksheet.set_column(first_col=1, last_col=1, cell_format=red_format)
worksheet.set_column(first_col=2, last_col=2, cell_format=blue_format)
for i in range(1, 1048576):
worksheet.set_row(row=i, cell_format=white_format)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.