Reputation: 430
I am using pyexcelerator
Python module to generate Excel files.
I want to apply bold style to part of cell text, but not to the whole cell.
How to do it?
Upvotes: 5
Views: 8691
Reputation: 110
Here is one solution which i had used for the same problem.
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()
Upvotes: 2
Reputation: 95911
This is an example from Excel documentation:
With Worksheets("Sheet1").Range("B1")
.Value = "New Title"
.Characters(5, 5).Font.Bold = True
End With
So the Characters property of the cell you want to manipulate is the answer to your question. It's used as Characters(start, length).
PS: I've never used the module in question, but I've used Excel COM automation in python scripts. The Characters property is available using win32com.
Upvotes: 3
Reputation: 47104
Found example here: Generate an Excel Formatted File Right in Python
Notice that you make a font object and then give it to a style object, and then provide that style object when writing to the sheet:
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)
Upvotes: 2