簡體   English   中英

如何使用 Python 將粗體樣式應用於 Excel 文件中的特定單詞?

[英]How to apply bold style to a specific word in Excel file using Python?

我正在使用pyexcelerator Python 模塊來生成 Excel 文件。 我想將粗體樣式應用於部分單元格文本,而不是整個單元格。 怎么做?

在這里找到示例: 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)

這是 Excel 文檔中的一個示例:

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

因此,您要操作的單元格的 Characters 屬性就是您問題的答案。 它用作 Characters( start , length )。

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

這是我用於同一問題的一種解決方案。

    import xlsxwriter
    workbook = xlsxwriter.Workbook(r'C:\workspace\NMSAutomation_001\FMGGUIAutomation\Libraries\Frontend\new_STICKERS_Final.xlsx')
####### two different formats
    bold   = workbook.add_format({'font_name':'Tahoma', 'bold': True, 'font_size':14})
    normal = workbook.add_format({'font_name':'Tahoma', 'font_size':11})

######## value is my string, bold and normal are my two different formats
    segments = [bold, value[:9], normal, value[9:]]
    worksheet.write_rich_string('A1', *segments) # 'A1' is cell position
    workbook.close()

暫無
暫無

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

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