Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can 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: 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.

like image 339
Derek Chadwell Avatar asked Oct 21 '14 14:10

Derek Chadwell


People also ask

How do I bold part of a text string in Excel?

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.

How do I bold certain cells in Excel?

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.

How do I bold the contents of a cell?

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.


2 Answers

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.

like image 83
Derek Chadwell Avatar answered Sep 30 '22 20:09

Derek Chadwell


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:

enter image description here

like image 21
jmcnamara Avatar answered Sep 30 '22 22:09

jmcnamara