2008-09-20 146 views
3

我正在使用pyexcelerator Python模塊來生成Excel文件。 我想將粗體樣式應用於部分單元格文本,但不適用於整個單元格。 如何做到這一點?如何使用Python將粗體樣式應用於Excel文件中的特定單詞?

+0

你能理解它通過在Excel中創建這樣的文件然後用pyexcelerator讀取它? – 2008-10-06 03:17:53

+0

`pyexcelerator`早已被`xlwt`取代。最近版本的`xlw​​t`支持Rich Text,在[這個問題]中進行了演示(http://stackoverflow.com/questions/14149748/format-individual-characters-in-a-single-excel-cell-with-python/14248375 )。爲了生成Excel 2007+文件(.xlsx),`xlsxwriter`是要走的路,它也支持Rich Text。 – 2013-12-17 22:22:11

回答

1

這是從Excel文檔中的一個例子:

With Worksheets("Sheet1").Range("B1") 
    .Value = "New Title" 
    .Characters(5, 5).Font.Bold = True 
End With 

所以,你要處理的細胞的字符屬性是回答你的問題。它用作字符(開始,長度)。

PS:我從來沒有使用過有問題的模塊,但我在Python腳本中使用了Excel COM自動化。 Characters屬性可以使用win32com。

+0

感謝您的回覆, 我實際上想知道如果這是可能的使用Python語言,Excel支持它肯定,但我找不到任何方式使用Python。 – Ashish 2008-09-20 18:51:08

2

發現這裏的例子:Generate an Excel Formatted File Right in Python

注意,你犯了一個字體對象,然後給它一個樣式對象,然後提供樣式對象寫入表時:

import pyExcelerator as xl 

def save_in_excel(headers,values): 
    #Open new workbook 
    mydoc=xl.Workbook() 
    #Add a worksheet 
    mysheet=mydoc.add_sheet("test") 
    #write headers 
    header_font=xl.Font() #make a font object 
    header_font.bold=True 
    header_font.underline=True 
    #font needs to be style actually 
    header_style = xl.XFStyle(); header_style.font = header_font 
    for col,value in enumerate(headers): 
     mysheet.write(0,col,value,header_style) 
    #write values and highlight those that match my criteria 
    highlighted_row_font=xl.Font() #no real highlighting available? 
    highlighted_row_font.bold=True 
    highlighted_row_font.colour_index=2 #2 is red, 
    highlighted_row_style = xl.XFStyle(); highlighted_row_style.font = highlighted_row_font 
    for row_num,row_values in enumerate(values): 
     row_num+=1 #start at row 1 
     if row_values[1]=='Manatee': 
      for col,value in enumerate(row_values): 
       #make Manatee's (sp) red 
       mysheet.write(row_num,col,value,highlighted_row_style) 
     else: 
      for col,value in enumerate(row_values): 
       #normal row 
       mysheet.write(row_num,col,value) 
    #save file 
    mydoc.save(r'C:testpyexel.xlt') 

headers=['Date','Name','Localatity'] 
data=[ 
['June 11, 2006','Greg','San Jose'], 
['June 11, 2006','Greg','San Jose'], 
['June 11, 2006','Greg','San Jose'], 
['June 11, 2006','Greg','San Jose'], 
['June 11, 2006','Manatee','San Jose'], 
['June 11, 2006','Greg','San Jose'], 
['June 11, 2006','Manatee','San Jose'], 
] 

save_in_excel(headers,data) 
相關問題