使用 ReportLab 有条件地为表格单元格着色

Min*_*Web 3 reportlab python-3.x

我已经使用 ReportLab 创建了一个表。我想根据它们的内容有条件地为单元格着色(在我的情况下,我希望负数为红色)。说清楚,我有条件代码工作,我不知道如何添加颜色。我试过的:

  • 使用<font color="...">标签。相反,标签被逐字包含在输出中。
  • 包装每个单元格Paragraph(...)(在这个答案中建议)。在这种情况下,单元格文本在每个字母后换行。
  • 将桌子包裹在Paragraph(...). 在这种情况下,reportlab错误(我相信由此产生的错误是TypeError: split() missing required positional argument: 'availHeight'
  • reportlab.platypus.tables.CellStylereportlab源代码中找到了,但无法弄清楚如何使用它。谷歌没有发现任何有用的东西,并且在reportlab文档中也没有提到。
  • 我想TableStyle(...)可以使用规则,但单元格不在表格中的预定位置(这是所有示例所假设的)。

帮助表示赞赏!

Ada*_*ler 5

使用TableStyle()将是一个可以接受的解决方案。您可以遍历数据并在满足条件时添加样式命令。

下面是一个例子:

import random
from reportlab.lib.pagesizes import letter
from reportlab.lib.colors import red
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle

# Generate random data with positive and negative values as list of lists.
data = []
for _ in range(20):
    data.append(random.sample(range(-10, 10), 5))
table_style = TableStyle([('ALIGN', (0, 0), (-1, -1), 'RIGHT')])
# Loop through list of lists creating styles for cells with negative value.
for row, values, in enumerate(data):
    for column, value in enumerate(values):
        if value < 0:
            table_style.add('TEXTCOLOR', (column, row), (column, row), red)

table = Table(data)
table.setStyle(table_style)
pdf = SimpleDocTemplate('example.pdf', pagesize=letter)
pdf.build([table])
Run Code Online (Sandbox Code Playgroud)