Markdown 格式化

此功能需要 xlwings PRO 并且至少为 v0.23.0 版本。

Markdown 提供了一种简单直观的方式来为单元格和形状中的文本组件设置样式。关于 Markdown 的介绍,参见例如,掌握 Markdown.

Markdown 支持目前处于早期阶段,仅支持以下内容:

  • 一级标题

  • 粗体(即强调)

  • 斜体(即强调)

  • 无序列表

它尚不支持嵌套对象,例如二级标题、项目符号内的粗体/斜体或嵌套的项目符号。

让我们通过一个示例来看看一切是如何工作的!

from xlwings.reports import Markdown, MarkdownStyle

mytext = """\
# Title

Text **bold** and *italic*

* A first bullet
* A second bullet

# Another Title

This paragraph has a line break.
Another line.
"""

sheet = xw.Book("Book1.xlsx").sheets[0]

# Range
sheet['A1'].clear()
sheet['A1'].value = Markdown(mytext)

# Shape: The following expects a shape like a Rectangle on the sheet
sheet.shapes[0].text = ""
sheet.shapes[0].text = Markdown(mytext)

运行此代码将为您提供这段格式优美的文本:

../../_images/markdown1.png

但为什么不使事物更时尚一点呢?通过提供一个MarkdownStyle对象,您可以定义自己的样式。让我们这样更改前面的例子:

from xlwings.reports import Markdown, MarkdownStyle

mytext = """\
# Title

Text **bold** and *italic*

* A first bullet
* A second bullet

# Another Title

This paragraph has a line break.
Another line.
"""

sheet = xw.Book("Book1.xlsx").sheets[0]

# Styling
style = MarkdownStyle()
style.h1.font.color = (255, 0, 0)
style.h1.font.size = 14
style.h1.font.name = 'Comic Sans MS'  # No, that's not a font recommendation...
style.h1.blank_lines_after = 0
style.unordered_list.bullet_character = '\N{heavy black heart}'  # Emojis are fun!

# Range
sheet['A1'].clear()
sheet['A1'].value = Markdown(mytext, style)  # <= provide your style object here

# Shape: The following expects a shape like a Rectangle on the sheet
sheet.shapes[0].text = ""
sheet.shapes[0].text = Markdown(mytext, style)

这是该代码的输出结果:

../../_images/markdown2.png

您可以覆盖所有属性,即您可以将强调从斜体更改为红色字体或您想要的其他任何样式:

>>> style.strong.bold = False
>>> style.strong.color = (255, 0, 0)
>>> style.strong
strong.color: (255, 0, 0)

Markdown 对象也可以与基于模板的报告一起使用,详见快速入门.

注意

macOS 当前由于 AppleScript/Excel 的一个 bug,不支持 Markdown 文本的格式化(粗体、斜体、颜色等)。不过,文本仍然会被正确渲染,包括项目符号。

另请参阅 API 参考:

  • Markdown class

  • MarkdownStyle class