2015-09-08 217 views
2

我正在使用pyopenxl來輸出一些excel電子表格,我遇到了字體條件格式的問題。我想強調的細胞比0小的用紅色和這裏的我做了什麼:openpyxl字體條件格式

from pyopenxl import formatting, styles 

red_font = styles.Font(size=self.font_size, bold=bold, color=self.red_color_font) 
red_fill = styles.PatternFill(start_color=self.red_color, end_color=self.red_color, fill_type='solid') 

self.ws.conditional_formatting.add(
    cell.coordinate, 
    formatting.CellIsRule(operator='lessThan', formula=['0'], fill=red_fill, font=red_font) 
) 

的字體所以我乾脆創建的樣式和填寫和應用他們對我的細胞。壞事是它不起作用。只要我從CellIsRule()中刪除字體格式,一切都會恢復正常,並且我的電池充滿了紅色。但問題是我需要改變顏色,沒有人知道我的代碼有什麼問題嗎?或者,也許與openpyxl?

+0

如何界定'red_color'和'red_color_font'?有紅色背景的紅色文本會導致紅色的單元格沒有可見的文本。 –

+0

它們是RGB格式的字符串,比如'self.red_color ='ffc7ce''和'self.red_color_font ='9c0103''。我還應該補充一點,在任何其他情況下,它們都能很好地工作,而不是使用條件格式:/ – Nhor

+0

您使用的是什麼版本的'openpyxl'? 'import openpyxl;打印openpyxl .__ version__'這對我來說似乎很好''2.2.6' –

回答

1

下面的代碼工作我使用2.2.6openpyxl版本:

from openpyxl import formatting, styles 

wb = Workbook() 
ws = wb.active 

red_color = 'ffc7ce' 
red_color_font = '9c0103' 

red_font = styles.Font(size=14, bold=True, color=red_color_font) 
red_fill = styles.PatternFill(start_color=red_color, end_color=red_color, fill_type='solid') 

for row in range(1,10):    
    ws.cell(row=row, column=1, value=row-5) 
    ws.cell(row=row, column=2, value=row-5) 

ws.conditional_formatting.add('A1:A10', formatting.CellIsRule(operator='lessThan', formula=['0'], fill=red_fill, font=red_font)) 
ws.conditional_formatting.add('B1:B10', formatting.CellIsRule(operator='lessThan', formula=['0'], fill=red_fill)) 
wb.save("test.xlsx") 

這顯示如下:

enter image description here

+0

好吧,如果這對你有用,我想這是我的MacOSX Numbers限制,它與Microsoft Excel不完全兼容。感謝您解決這個問題! – Nhor