【问题标题】:How to align a single cell in reportlab Table如何在reportlab表格中对齐单个单元格
【发布时间】:2016-09-23 22:24:51
【问题描述】:

我正在使用 创建一个表格,我想将下表中的单个单元格(向右)对齐:

我想将包含“职业”的单元格右对齐

这是我的代码:

studentProfileData = [
                ['Application Form No', ''],
                ['Name', userData['studentDetails']["firstName"] + " " +userData['studentDetails']["lastName"]],
                ['Course opted for', userData['courseDetails']["courseOptedFor"]],
                ['Specific Course Name', courseMapping["Name"]],
                ['Category', userData['studentDetails']['caste']],
                ['Religion', userData['studentDetails']['religion']],
                ['Fathers'+ "'" +'s Name', userData['studentDetails']['religion']],
                ['Occupation', userData['studentDetails']['fOccupation']],
                ['Phone No', ""],
                ['Term', ""]
            ]

        colwidths = [3 * inch, 1.5 * inch, inch]

        # Two rows with variable height
        rowheights = [.5*inch] * len(studentProfileData)
        studentProfile = Table(studentProfileData, colwidths, rowheights, hAlign='LEFT')

        studentProfile.setStyle(TableStyle([
                ('ALIGN', (0, 0), (0, -1), "LEFT"),
                ('FONTSIZE', (0,0), (-1, -1), 13),
            ]))

        parts = [ page1Head, studentProfile]

【问题讨论】:

  • 你的意思是单元格而不是列?正如问题所说“我想将职业对齐”。
  • 我只想对齐文本“职业”

标签: reportlab python django pdf-generation reportlab


【解决方案1】:

为了对齐 Reportlab Table 中的单个单元格,我们需要将 TableStyle 更改为以下内容:

TableStyle([
            ('ALIGN', (0, 0), (0, -1), "LEFT"),
            ('FONTSIZE', (0,0), (-1, -1), 13),
            ('ALIGN', (0, 7), (0, 7), "RIGHT"),
        ])

之所以有效,是因为我们现在告诉(0,7)(0,7) 之间区域中的单元格应该右对齐,因为该区域中唯一的单元格是包含Occupation 的单元格,只有该文本是对齐的。

另一种方法是在表格中使用Paragraph 而不仅仅是String,在这种情况下,我们可以使用Paragraph 进行对齐,因为它将填充单元格的整个宽度。

段落示例

pageTextStyleCenter = ParagraphStyle(name="left", alignment=TA_CENTER, fontSize=13, leading=10)

[ Paragraph("Occupation", pageTextStyleCenter) , userData['studentDetails'].get('fOccupation', "-")]

【讨论】:

  • 我是用Paragraph解决问题的,谢谢大家的帮助
  • 感谢您添加示例,我在其中更改了一件事,这与样式完全无关,即您可以使用dict.get(key, alternative) 来执行您所做的操作,而不是检查字典是否有键:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-21
  • 2022-11-28
  • 2019-06-09
  • 1970-01-01
  • 2010-12-14
相关资源
最近更新 更多