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: this is the command you run to fix it
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.
In Excel, if you want to bold or underline specific words within a cell, you can just select the words you want and click Home-> Bold and Underline under Font tab. Then the specific words will be bold and underlined.
Select the cell(s) you want to modify. Click the Bold (B), Italic (I), or Underline (U) command on the Home tab. In our example, we'll make the selected cells bold. The selected style will be applied to the text.
In the Find and Replace dialog box, click on the Options button. In the Find what section, go to the Format drop-down and select 'Choose Format From Cell'. Select any cell which has the text in bold font format.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With