如何在 reportlab 中的 table 单元格内创建 table

How to create a table inside a table cell in reportlab

我现在需要在 table 单元格内创建一个 table,这是数据中的描述字段,它本身就是一个列表。我需要从该列表中创建一个 table。 下面是我目前用来在 reportlab 中创建普通 table 的代码,我只需要在 table 的描述字段中的 table 中插入一个 table ,描述字段本身将是数据列表中的一个列表。

from reportlab.lib.pagesizes import A1
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.platypus import BaseDocTemplate, Frame, PageTemplate, Paragraph, Table, TableStyle
from functools import partial
from reportlab.lib import colors
from reportlab.platypus.doctemplate import SimpleDocTemplate

cm = 2.58
styles = getSampleStyleSheet()

data = [["Register","S.No.", "PON","Description","Quantity","Cost","Supplier","DOR","RVN","Alloted Lab",
"TON","TOD","Transferred Dept./Lab","Remarks"],
    ["Register REG1", 12, 56, Paragraph('Here is large field retrieve from database Here is large field retrieve from database Here is large field retrieve from database', styles['Normal']), 4,"4466561", "SHAKTI", "2021-09-05", 778, "Iron Man Lab", 4566, "2021-09-04", "Tony Stark Lab", "This is the remark for REG1"]]

for i in range(0,6):
    data.extend(data)

doc = SimpleDocTemplate('testtable.pdf', pagesize=A1)

table = Table(data, repeatRows=1)

# add style

numberofcols = len(data[0])


style = TableStyle([
    ('BACKGROUND', (0,0), (numberofcols,0), colors.green),
    ('TEXTCOLOR',(0,0),(-1,0),colors.whitesmoke),
    ('ALIGN',(0,0),(-1,-1),'CENTER'),
    ('FONTNAME', (0,0), (-1,0), 'Courier-Bold'),
    ('FONTSIZE', (0,0), (-1,0), 14),
    ('BOTTOMPADDING', (0,0), (-1,0), 12),
    ('BACKGROUND',(0,1),(-1,-1),colors.beige),
])
table.setStyle(style)

# 2) Alternate backgroud color -- formatting
rowNumb = len(data)
for i in range(1, rowNumb):
    if i % 2 == 0:
        bc = colors.burlywood
    else:
        bc = colors.beige
    
    ts = TableStyle(
        [('BACKGROUND', (0,i),(-1,i), bc)]
    )
    table.setStyle(ts)

# 3) Add borders -- formatting 
ts = TableStyle(
    [
    ('BOX',(0,0),(-1,-1),2,colors.black),
    ('LINEBEFORE',(2,1),(2,-1),2,colors.red),
    ('LINEABOVE',(0,2),(-1,2),2,colors.green),
    ('GRID',(0,1),(-1,-1),2,colors.black),
    ]
)
table.setStyle(ts)

elems = []

# elems.append("TABLE TITLE")
elems.append(table)

doc.build(elems)

对于这种情况,reportlab 的文档没有帮助如何实现这一点。我的回答主要基于此评论 here。要在一行中创建一个 Table,您必须首先创建一个新的 table 并将它们添加到您的“原始 table”。下面我将解释步骤:

from reportlab.platypus import SimpleDocTemplate, TableStyle, Table

# Creating a simple pdfdoc = SimpleDocTemplate(aa)
story = []

# Set a table style
table_style = TableStyle(
    [
        ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
        ('BOX', (0,0), (-1,-1), 0.25, colors.black),
    ]
)

# Creating mock data and cols to add a new table inside the third a row
data_table = [
    ['Col1', 'Col2'], 
    ['aaa', 'bbb'],
    [Table([['data to add as third row', 'a']], style=table_style)]
]


final_table = Table(data_table, style=table_style)
story.append(final_table)
doc.build(story)