简体   繁体   English

如何使用python在excel单元格中仅加粗字符串的一部分

[英]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. 我正在使用win32com填写带有一些分析信息的excel电子表格。 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. 我似乎无法弄清楚如何使用混合格式的python将文本放入单元格。

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. 选择对象有一个Characters属性,但我找不到任何关于它的作用的文档。 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: Per @ ron-rosenfield,将其关闭的VBA代码如下:

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

And similarly, there is a Characters object attribute of the excel WorkSheet's Range 同样,excel WorkSheet的Range有一个Characters对象属性

>>> 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) 但是,使用该对象访问范围所需的方法是GetCharacters(start,length)(索引从excel com方法的常规开始为1)

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. 虽然您正在寻找问题正文中的win32com解决方案,但我会指出通过标题来到这里的任何人都可以使用XlsxWriter在Python中实现这一点。

Example : 示例

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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