如何使用xlwtpythonexcel将样式应用于整行?

2024-10-01 13:39:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试应用一种样式,如果其中一列包含值“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”的任何行都高亮显示?谢谢!在


Tags: 代码inforifcount样式colelse
1条回答
网友
1楼 · 发布于 2024-10-01 13:39:14

您的主要问题是,您的代码在写入行中的一些单元格后,正在检查“资产”。在写入行中的任何单元格之前,您需要进行“整行使用什么样式”测试。在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

同时也提出了一个问题:你是否应该对数字和文本使用不同的样式。在

相关问题 更多 >