【问题标题】:Conditionally Color Table Cells with ReportLab使用 ReportLab 有条件地为表格单元格着色
【发布时间】:2018-02-27 18:23:45
【问题描述】:

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

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

帮助表示赞赏!

【问题讨论】:

    标签: python-3.x reportlab


    【解决方案1】:

    使用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])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-04
      • 2023-04-07
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-15
      • 1970-01-01
      相关资源
      最近更新 更多