如何在reportlab中的表单元格中创建表



我需要在表格单元格内创建一个表格,表格单元格是数据中的描述字段,它本身就是一个列表。我需要把那张单子做成一张桌子。以下是我目前用于在reportlab中创建普通表的代码,我只需要在该表的描述字段中的表中插入一个表,描述字段本身就是数据列表中的列表。

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的文档对如何实现这一点没有帮助。我的回答主要基于这里的评论。要在一行中创建一个表,您必须首先创建一个新表并将它们添加到您的";原始表格";。Bellow我将解释步骤:

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)

最新更新