如何使用python在Excel单元格中仅粗体显示字符串的一部分 [英] How Do I Bold only part of a string in an excel cell with python
问题描述
我正在使用win32com来填写带有一些分析信息的excel电子表格.我有一个要设置为这种形式的单元格:
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:
这是问题的描述:这是您用来修复它的命令
我似乎无法弄清楚如何使用混合格式的python将文本放入单元格中.
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
选择对象具有Characters属性,但是找不到有关其功能的任何文档.我在这里有点茫然,我可以帮忙.
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.
谢谢
推荐答案
我终于找到了它,并在此处发布,因此我们的堆栈溢出霸主也可以随时得到答案.
I finally found it, posting here so our stack overflow overlords can have the answer on hand as well.
对于每个@ ron-rosenfield,实现这一目标的VBA代码如下:
Per @ron-rosenfield, the VBA code to pull this off looks like:
Range("A1").Characters(2,5).Font.Bold = true
类似地,还有一个Excel WorkSheet范围的Characters对象属性.
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>
但是,您需要使用该对象访问范围的方法是GetCharacters(start,length)(与excel com方法一样,索引通常从1开始)
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.
这篇关于如何使用python在Excel单元格中仅粗体显示字符串的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!