如何在ReportLab中调整列宽以适应内容?

9

我正在使用ReportLab工具在Python中进行开发。我需要生成PDF格式的报告。数据将从数据库检索并插入表格中。 以下是简单的代码:

from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
from reportlab.lib.units import inch
doc = SimpleDocTemplate("simple_table.pdf", pagesize=letter)
elements = []

data= [['00', '01', '02', '03', '04'],
       ['10', 'Here is large field retrieve from database', '12', '13', '14'],
       ['20', '21', '22', '23', '24'],
       ['30', '31', '32', 'Here is second value', '34']]
t=Table(data)
columnWidth = 1.9*inch;
for x in range(5):
        t._argW[x]= cellWidth
elements.append(t)
doc.build(elements)

有三个问题:

  1. 单元格中的长数据会与同行的其他单元格重叠。
  2. 当我手动增加列宽度时,例如 cellWidth = 2.9*inch;,页面不可见且无法左右滚动。
  3. 我不知道如何将数据追加到单元格中,也就是说,如果数据量很大,应该将其附加到同一单元格中的下一行。

我如何遇到这个问题?

3个回答

10

首先,我不会像你那样设置列大小。只需像这样向 Table 传递 colWidths 参数:

Table(data, colWidths=[1.9*inch] * 5)

现在来看看你的问题。如果您不设置colWidth参数,reportlab将为您做这个,并根据您的数据间隔列。如果这不是您想要的,您可以将数据封装到段落中,就像Bertrand所说的那样。下面是您代码的修改示例:

from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch
styles = getSampleStyleSheet()
doc = SimpleDocTemplate("simple_table.pdf", pagesize=letter)
elements = []

data= [['00', '01', '02', '03', '04'],
       ['10', Paragraph('Here is large field retrieve from database', styles['Normal']), '12', '13', '14'],
       ['20', '21', '22', '23', '24'],
       ['30', '31', '32', 'Here is second value', '34']]
t=Table(data)
elements.append(t)
doc.build(elements)

我想你会理解的。


1

今天我也遇到了同样的问题。我在寻找一种解决方案,使我只能调整单个列的大小——这个列与其他列具有非常不同的内容长度——并且让 Reportlab 为我完成其余工作。

以下是我的解决方法:

Table(data, colWidths=[1.9*inch] + [None] * (len(data[0]) - 1))

这指定了只有第一列。但是,当然你也可以轻松地将数字放在None之间的任何位置。

-1

嗨,当我调整表格内容大小时,我遇到了同样的问题,后来我找到了解决方案。这个解决方案可能会帮助你,并解决你在这里提到的所有3个问题。

from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
from reportlab.lib.units import inch
doc = SimpleDocTemplate("simple_table.pdf", pagesize=letter)
elements = []

data= [['00', '01', '02', '03', '04'],
       ['10', 'Here is large field retrieve from database', '12', '13', '14'],
       ['20', '21', '22', '23', '24'],
       ['30', '31', '32', 'Here is second value', '34']]
t=Table(data,colWidths=[1.9*inch]*5, rowHeights=[0.9*inch] *4)
#colWidth = size * number of columns
#rowHeights= size * number of rows
elements.append(t)
doc.build(elements)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接