2012-02-23 81 views
1

我想應用一個樣式,如果其中一列包含值「Assets」,將突出顯示整行。下面的代碼將僅突出顯示其中包含「Assets」的列,而不是整行。有沒有辦法將風格應用於整行?如何使用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) 

正如您所看到的,根據行我應用不同的樣式。我如何做到這一點,以便包含關鍵字「資產」的任何行都將突出顯示?謝謝!

+0

你爲什麼接受根據你自己的意見不起作用的答案? – 2012-03-03 21:19:25

回答

1

您的主要問題是您的代碼在行中寫入了一些單元格後正在檢查「資產」。您需要在之前,在行中寫入任何單元格,然後執行「整行使用什麼樣式」的測試。在xlwt 對象上設置樣式不起作用;這是默認風格,用於與其他格式不適用的單元格一起使用。

其他問題:

包含值 「資產」。下面的代碼將僅突出顯示 列中包含「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 

也提出了一個問題,即你是否應該有不同的數字風格d文本。

相關問題