如何使用Python对Excel文件中的特定单词应用粗体样式?

2024-05-10 15:56:22 发布

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

我正在使用pyexceleratorPython模块生成Excel文件。 我想将粗体样式应用于部分单元格文本,但不应用于整个单元格。 怎么做?


Tags: 模块文件文本样式excelpyexceleratorpython
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)

这是Excel文档中的一个示例:

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

因此,要操作的单元格的字符属性就是问题的答案。它用作字符(开始长度)。

注:我从未使用过这个模块,但我在python脚本中使用过Excel COM自动化。Characters属性在使用win32com时可用。

相关问题 更多 >