富文本#

通常,样式应用于单个单元格中的所有内容。但是,富文本允许格式化字符串中的部分文本。

富文本对象可以包含非格式化文本和 TextBlock 对象的混合,TextBlock 对象包含 InlineFont 样式和要格式化的文本。结果是 CellRichText 对象。

from openpyxl.cell.text import InlineFont
from openpyxl.cell.rich_text import TextBlock, CellRichText
rich_string1 = CellRichText(
    'This is a test ',
    TextBlock(InlineFont(b=True), 'xxx'),
    'yyy')
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
Cell In[1], line 1
----> 1 from openpyxl.cell.text import InlineFont
      2 from openpyxl.cell.rich_text import TextBlock, CellRichText
      3 rich_string1 = CellRichText(
      4     'This is a test ',
      5     TextBlock(InlineFont(b=True), 'xxx'),
      6     'yyy')

ModuleNotFoundError: No module named 'openpyxl'

InlineFont 对象实际上与 Font 对象相同,但是使用不同的属性名 rFont 作为字体的名称。不幸的是,这是 OOXML 所要求的,并且无法避免。

inline_font = InlineFont(rFont='Calibri', # Font name
                         sz=22,           # in 1/144 in. (1/2 point) units, must be integer
                         charset=None,    # character set (0 to 255), less required with UTF-8
                         family=None,     # Font family
                         b=True,          # Bold (True/False)
                         i=None,          # Italics (True/False)
                         strike=None,     # strikethrough
                         outline=None,
                         shadow=None,
                         condense=None,
                         extend=None,
                         color=None,
                         u=None,
                         vertAlign=None,
                         scheme=None)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[2], line 1
----> 1 inline_font = InlineFont(rFont='Calibri', # Font name
      2                          sz=22,           # in 1/144 in. (1/2 point) units, must be integer
      3                          charset=None,    # character set (0 to 255), less required with UTF-8
      4                          family=None,     # Font family
      5                          b=True,          # Bold (True/False)
      6                          i=None,          # Italics (True/False)
      7                          strike=None,     # strikethrough
      8                          outline=None,
      9                          shadow=None,
     10                          condense=None,
     11                          extend=None,
     12                          color=None,
     13                          u=None,
     14                          vertAlign=None,
     15                          scheme=None)

NameError: name 'InlineFont' is not defined

幸运的是,如果你已经有 Font 对象,你可以简单地用现有的 Font 对象初始化 InlineFont 对象:

from openpyxl.cell.text import Font
font = Font(name='Calibri',
            size=11,
            bold=False,
            italic=False,
            vertAlign=None,
            underline='none',
            strike=False,
            color='00FF0000')
inline_font = InlineFont(font)
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
Cell In[3], line 1
----> 1 from openpyxl.cell.text import Font
      2 font = Font(name='Calibri',
      3             size=11,
      4             bold=False,
   (...)
      8             strike=False,
      9             color='00FF0000')
     10 inline_font = InlineFont(font)

ModuleNotFoundError: No module named 'openpyxl'

您可以单独创建 InlineFont 对象,并在以后使用它们。这使得工作与富文本更干净和更容易:

big = InlineFont(sz="30.0")
medium = InlineFont(sz="20.0")
small = InlineFont(sz="10.0")
bold = InlineFont(b=True)
b = TextBlock
rich_string2 = CellRichText(
    b(big, 'M'),
    b(medium, 'i'),
    b(small, 'x'),
    b(medium, 'e'),
    b(big, 'd'))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[4], line 1
----> 1 big = InlineFont(sz="30.0")
      2 medium = InlineFont(sz="20.0")
      3 small = InlineFont(sz="10.0")

NameError: name 'InlineFont' is not defined

例如:

red = InlineFont(color='FF000000')
rich_string1 = CellRichText(['When the color ', TextBlock(red, 'red'), ' is used, you can expect ', TextBlock(red, 'danger')])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[5], line 1
----> 1 red = InlineFont(color='FF000000')
      2 rich_string1 = CellRichText(['When the color ', TextBlock(red, 'red'), ' is used, you can expect ', TextBlock(red, 'danger')])

NameError: name 'InlineFont' is not defined

CellRichText 对象是从 list 中派生出来的,并且可以这样使用。

空白符#

CellRichText 对象在将元素呈现为字符串或保存文件时,不会在元素之间添加空格。

t = CellRichText()
t.append('xx')
t.append(TextBlock(red, "red"))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[6], line 1
----> 1 t = CellRichText()
      2 t.append('xx')
      3 t.append(TextBlock(red, "red"))

NameError: name 'CellRichText' is not defined

还可以将其强制转换为 str 以只获得文本,而不进行格式化。

str(t)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[7], line 1
----> 1 str(t)

NameError: name 't' is not defined

编辑富文本#

由于编辑带有格式的大块文本可能很棘手,as_list() 方法返回字符串列表以简化索引。

l = rich_string1.as_list()
l
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[8], line 1
----> 1 l = rich_string1.as_list()
      2 l

NameError: name 'rich_string1' is not defined
l.index("danger")
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[9], line 1
----> 1 l.index("danger")

NameError: name 'l' is not defined
rich_string1[3].text = "fun"
str(rich_string1)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[10], line 1
----> 1 rich_string1[3].text = "fun"
      2 str(rich_string1)

NameError: name 'rich_string1' is not defined

富文本单元格#

富文本对象可以直接分配给单元格:

from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws['A1'] = rich_string1
ws['A2'] = 'Simple string'
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
Cell In[11], line 1
----> 1 from openpyxl import Workbook
      2 wb = Workbook()
      3 ws = wb.active

ModuleNotFoundError: No module named 'openpyxl'