[英]How to force Python XlsxWriter to write to cell in custom format
[英]how to use python xlsxwriter to conditionally format on cell value
我想輸出條件格式的Excel工作表,其中每一列的條件取決於第一行中的值。 使用所示的數據幀,單元格A2,A4,B3,B4,C4,C5,D4和E4將突出顯示為紅色。
import xlsxwriter
data = [
[1, 1, 5, 'A', 1],
[1, 4, 4, 'B', 0],
[2, 1, 5, 2, 2],
[1, 1, 5, 'A', 1],
]
wb = xlsxwriter.Workbook('testout.xlsx')
ws = wb.add_worksheet()
formatyellow = wb.add_format({'bg_color':'#F7FE2E'})
formatred = wb.add_format({'bg_color':'#FF0000'})
i=0
for row, row_data in enumerate(data):
print (row)
print (row_data)
ws.write_row(row, 0, row_data)
i += 1
ws.conditional_format(0,1,4,5, {'type':'text',
'criteria':'containing',
'value':'B',
'format':formatyellow})
ws.conditional_format(0,1,4,5, {'type':'cell',
'criteria':'==',
'value':'A$1',
'format':formatred})
有沒有一種使用xlsxwriter完成此操作的方法?
在ws.conditional_format
更改索引后,我能夠產生所需的結果。 請記住, xslxwriter
使用零索引,因此row=0
, col=0
對應於單元格A0
。 另外,我必須在功能的末尾添加wb.close()
import xlsxwriter
data = [
[1, 1, 5, 'A', 1],
[1, 4, 4, 'B', 0],
[2, 1, 5, 2, 2],
[1, 1, 5, 'A', 1],
]
wb = xlsxwriter.Workbook('testout.xlsx')
ws = wb.add_worksheet()
formatyellow = wb.add_format({'bg_color':'#F7FE2E'})
formatred = wb.add_format({'bg_color':'#FF0000'})
i=0
for row, row_data in enumerate(data):
print (row)
print (row_data)
ws.write_row(row, 0, row_data)
i += 1
ws.conditional_format(1,0,3,4, {'type':'text', #Start from row 1 ("B") and column 0 (1)
'criteria':'containing',
'value':'B',
'format':formatyellow})
ws.conditional_format(1,0,3,4, {'type':'cell',
'criteria':'==',
'value':'A$1',
'format':formatred})
wb.close()
輸出:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.