如何使用XLWT Python Excel将整个样式应用于整行?

我试图应用一种风格,如果其中一列包含值“资产”将突出显示整个行。 下面的代码将仅突出显示“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”。 你写行中的任何单元格之前,你需要做“你整个行使用什么风格”的testing。 在xlwt Row对象上设置样式不起作用; 这是默认样式,用于没有任何其他格式应用的单元格。

其他问题:

包含值“资产”。 下面的代码将只突出显示“资产”的列

这是不明确的。 假设一个单元格的值恰好等于“权益资产”。 您想做什么? 注意:你的代码会突出显示这样一个单元格和那些在右边的单元格。 此外,“资产”承载单元格应该是第一个(例如在您对另一个答案的评论中)或任何单元格(根据您的代码)并不明显。

你对variables名称的一些select使你的代码非常难以阅读,例如, 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 

也提出了你是否应该有不同的数字和文字风格的问题。