簡體   English   中英

如何使用XLWT Python Excel將樣式應用於整個行?

[英]How do I apply a style to the whole row using XLWT Python Excel?

我正在嘗試應用一種樣式,如果其中一列包含值“資產”,則該樣式將突出顯示整個行。 下面的代碼將僅突出顯示其中包含“資產”的列,而不突出顯示整個行。 有沒有一種方法可以將樣式應用於整個行?

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)

如您所見,根據行的不同,我將應用不同的樣式。 如何使包含關鍵字“資產”的任何行突出顯示? 謝謝!

您的主要問題是您的代碼在行中寫入了一些單元格之后正在檢查“資產”。 在行中寫入任何單元格之前,您需要進行“用於整個行的樣式”測試。 xlwt Row對象上設置樣式無效。 這是默認樣式,用於沒有應用其他格式的單元格。

其他問題:

包含值“資產”。 下面的代碼將僅突出顯示其中包含“資產”的列

這是模棱兩可的。 假設一個像元值​​正好等於“股票資產”; 你想讓我做什么? 注意:您的代碼將突出顯示此類單元格及其右側的單元格。 同樣不清楚“資產”單元格應該是第一個(在您對另一個答案的評論中的示例)還是任何單元格(根據您的代碼)。

對於變量名的某些選擇使您的代碼很難閱讀,例如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

並提出了一個問題,即您是否應該對數字和文本使用不同的樣式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM