进一步 comments
文本块可以是整个单词、两个或多个单词或单词的一部分,具体取决于字体更改所在的位置.如果空格继承的是默认字体,而不是上一个或下一个单词的样式,您也可能会将空格字符[单词之间]视为单独的文本块.
For example, given the following text in the cell
we would expect 3 textblocks, one for each word.
要获得字体细节,您可能希望使用for循环循环文本块,并打印出每个文本块的字体样式,如下所示;
In the example code Either 'b' or 'bold' can be used to access the textblock bold state;
e.g.
font_style.b
and
font_style.bold
return the status of bolding in the text block. The same goes for italic where either .i
or .italic
can be used and for underline, .u
or .underline
can be used.
import openpyxl
path="foo.xlsx"
wb_obj = openpyxl.load_workbook(path, rich_text=True)
sheet_obj = wb_obj.active
cell_obj = sheet_obj.cell(row=1, column=1)
for textblock_item in cell_obj.value:
### Check the textblock_item is an Openpyxl RichText TextBlock
print(f"textblock_item type: '{type(textblock_item)}'")
### Type should be 'openpyxl.cell.rich_text.TextBlock'
### Either of the following two lines should print the actual text in the block
print(f"Block of text: '{textblock_item.text}'")
print(f"Block of text: '{textblock_item}'")
font_style = textblock_item.font
print(f"Font Enhancements; Bold: {font_style.b}, "
f"Italic: {font_style.italic}, "
f"Underline: {font_style.underline}")
print(f"Font Size: {font_style.size}")
print(f"Font family: {font_style.rFont}")
if font_style.color is not None:
if isinstance(font_style.color.index, str):
print(f"Font Colour: {font_style.color.rgb}")
else:
print(f"Font Colour: Theme {font_style.color.theme}, Tint: {font_style.color.tint}")
else:
print(f"Font Colour: None")
print("-----------------------------------\n")
其输出将是
Block of text: 'bold '
Font Enhancements; Bold: True, Italic: False, Underline: None
Font Size: 10.0
Font family: Calibri
Font Colour: FF00FF00
-----------------------------------
Block of text: 'itallic '
Font Enhancements; Bold: False, Italic: True, Underline: None
Font Size: 11.0
Font family: Arial
Font Colour: FFFF0000
-----------------------------------
Block of text: 'underline '
Font Enhancements; Bold: False, Italic: False, Underline: single
Font Size: 12.0
Font family: Verdana
Font Colour: FF0000FF
-----------------------------------
您可以看到每个单词的尾随空格都包括在单词块中,但它可能是单独的,如前所述,因此如果有问题,您可以在循环中包括对它的判断.
如前所述,每个块分隔字体样式,因此如果在同一示例中,第一个单词‘粗体’只有‘L’下划线(没有其他字体更改),则会将该文本块更改为由单词中的字符组成的三个单独的块.
示例
Block of text: 'bo'
Font Enhancements; Bold: True, Italic: False, Underline: None
Font Size: 10.0
Font family: Calibri
Font Colour: FF00FF00
-----------------------------------
Block of text: 'l'
Font Enhancements; Bold: True, Italic: False, Underline: single
Font Size: 10.0
Font family: Calibri
Font Colour: FF00FF00
-----------------------------------
Block of text: 'd '
Font Enhancements; Bold: True, Italic: False, Underline: None
Font Size: 10.0
Font family: Calibri
Font Colour: FF00FF00
-----------------------------------
... with the rest of the words as shown previously.