您的主要问题是,您的代码在写入行中的一些单元格后,正在检查“资产”。在写入行中的任何单元格之前,您需要进行“整行使用什么样式”测试。在xlwtRow对象上设置样式不起作用;这是一个用于没有应用任何格式的单元格的默认样式。在
其他问题:contains the value "Assets". The code below will highlight only the
column with "Assets" in it
这是模棱两可的。假设一个单元格的值正好等于“权益资产”;你想怎么做?注意:您的代码将突出显示这样一个单元格及其右侧的单元格。同样,不明显的是,承载“资产”的单元格应该是第一个(在您对另一个答案的注释中的示例)还是任何单元格(根据您的代码)。在
您对变量名的某些选择使代码很难阅读,例如,row是单元格值的列表,而{}是列索引。尽可能使用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函数很好奇。。。我会用这个:
^{pr2}$
这会自动导致:if common_style == rowStyle:
try:
cell_value = float(cell_value)
except ValueError:
pass
同时也提出了一个问题:你是否应该对数字和文本使用不同的样式。在