我正在尝试应用一种样式,如果其中一列包含值“Assets”,则该样式将突出显示整行。下面的代码将仅突出显示其中包含“Assets”的列,而不是整行。有没有办法将样式应用到整行?
for row in csv_input:
#Iterate through each column
for col in range(len(row)):
#Apply different styles depending on row
if row_count == 0:
sheet.write(row_count,col,row[col],headerStyle)
elif row_count == 3:
sheet.write(row_count,col,row[col],subheadStyle)
elif "Assets" in row[col]:
sheet.write(row_count,col,row[col],highlightStyle)
else:
if (is_number(row[col]) == True):
sheet.write(row_count,col,float(row[col]),rowStyle)
else:
sheet.write(row_count,col,row[col],rowStyle)
正如您所看到的,根据行我应用不同的样式。如何才能使包含关键字“Assets”的任何行都突出显示?谢谢!
答案 0 :(得分:1)
您的主要问题是您的代码在行中写入了一些单元格后正在检查“资产”。您需要在之前执行“用于整行的样式”测试,然后在行中写入任何单元格。在xlwt
Row
对象上设置样式不起作用;这是一个默认样式,用于没有应用任何格式的单元格。
其他问题:
包含值“Assets”。下面的代码将仅突出显示 其中包含“资产”的栏目
这是含糊不清的。假设一个单元格值恰好等于“Equity Assets”;你想让我做什么?注意:您的代码将突出显示此类单元格及其右侧的单元格。此外,“资产” - 承载单元格应该是第一个(在您对另一个答案的评论中的示例)还是任何单元格(根据您的代码)都不明显。
您对变量名称的一些选择会使您的代码难以阅读,例如row
是单元格值列表,但col
是列索引。尽可能使用enumerate()
。
尝试这样的事情:
for row_index, cell_values in enumerate(csv_input):
# Determine what style to use for the whole row
if row_index == 0:
common_style = headerStyle
elif row_index == 3:
common_style = subheadStyle
elif "Assets" in cell_values:
# perhaps elif any("Assets" in cell_value for cell_value in cell_values):
# perhaps elif cell_values and cell_values[0] == "Assets":
# perhaps elif cell_values and "Assets" in cell_values[0]:
common_style = highlightStyle
else:
common_style = rowStyle
# Iterate over the columns
for col_index, cell_value in enumerate(cell_values):
if common_style == rowStyle and is_number(cell_value):
cell_value = float(cell_value)
sheet.write(row_index, col_index, cell_value, common_style)
我对is_number
功能感到好奇......我会用它:
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
自动导致:
if common_style == rowStyle:
try:
cell_value = float(cell_value)
except ValueError:
pass
并且还提出了一个问题,即你是否应该为数字和文本设置不同的样式。