简体   繁体   中英

How Do I Bold only part of a string in an excel cell with python

I'm using win32com to fill out an excel spreadsheet with some analytic information. I have a cell that I want to be in this form:

This is the problem description:

I can't seem to figure out how to get the text into the cell with python with mixed formatting.

import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Add()
ws = wb.Worksheets("Sheet1")
excel.Visible=True
sel = excel.Selection
sel.Value = "this is the command you run to fix it"
sel.Font.Bold = True
ws.Cells(1,1).Value = 'This is the problem description' + sel.Value  #makes the whole cell bold
ws.Cells(1,1).Value = "{} {}".format("this is the problem desc",sel) #makes the whole cell bold

The selection object has a Characters attribute, but I can't find any documentation on what it does. I'm at a bit of a loss here, I could use an assist.

Thanks

I finally found it, posting here so our stack overflow overlords can have the answer on hand as well.

Per @ron-rosenfield, the VBA code to pull this off looks like:

Range("A1").Characters(2,5).Font.Bold = true 

And similarly, there is a Characters object attribute of the excel WorkSheet's Range

>>> ws.Range("A1").Characters
<win32com.gen_py.Microsoft Excel 14.0 Object Library.Characters 967192>

HOWEVER, the method you need to access a range with that object is GetCharacters(start, length) (index starts at 1 as per usual with the excel com methods)

ws.Range("A1").GetCharacters(2,4).Font.Bold = True

You can use this command to update the boldness of characters in a cell after the fact.

Although you are looking for a win32com solution in the body of your question I'll point out for anyone who gets here via the title that this is also possible in Python with XlsxWriter.

Example :

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM