合并reportlab表中的列

时间:2018-08-06 13:52:48

标签: python pdf reportlab

我正在尝试使用reportlab创建一个表,该表可以具有需要在所有或某些列之间合并的值。

这是我的示例,我需要在所有五列中合并第一行。我尝试使用('SPAN', (0, 0), (-1, -1))行,在此示例中对此行进行了注释,以便您可以看到表的初始外观。如果取消注释该行,则只会将第一行写入pdf。

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import cm
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import Paragraph, Table, TableStyle
from reportlab.lib.enums import TA_JUSTIFY, TA_LEFT, TA_CENTER
from reportlab.lib import colors

width, height = A4
styles = getSampleStyleSheet()
styleN = styles["BodyText"]
styleN.alignment = TA_LEFT
styleBH = styles["Normal"]
styleBH.alignment = TA_CENTER

def coord(x, y, unit=1):
    x, y = x * unit, height - y * unit
    return x, y

# Headers
head = Paragraph('''<b>Table head</b>''', styleBH)
hID = Paragraph('''<b>ID</b>''', styleBH)
hcount = Paragraph('''<b>count</b>''', styleBH)
hcandidate = Paragraph('''<b>candidate</b>''', styleBH)
hprice = Paragraph('''<b>price</b>''', styleBH)
htotal_price = Paragraph('''<b>total price</b>''', styleBH)

# Texts
description = Paragraph('long paragraph', styleN)
ID = Paragraph('1', styleN)
count = Paragraph('120', styleN)
price = Paragraph('$52.00', styleN)
total_price = Paragraph('$6240.00', styleN)

data = [[head],
    [hID, hcount, hcandidate, hprice, htotal_price],
        [ID, description, description, price, total_price]]

table = Table(data, colWidths=[2.05 * cm, 2.7 * cm, 5 * cm,
                               3 * cm, 3 * cm])

table.setStyle(TableStyle([
    # ('SPAN', (0, 0), (-1, -1)),
    ('GRID', (0, 0), (-1, -1), 0.25, colors.grey),
    ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
    ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
]))

c = canvas.Canvas('output_pdf.pdf', pagesize=A4)
table.wrapOn(c, width, height)
table.drawOn(c, *coord(1.8, 9.6, cm))
c.save()

我在这里浏览了一些问题,但是没有找到明确的示例来说明如何执行此操作。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:2)

(0,0)表示最左上角的起始单元格,而(-1,-1)表示最右下角的终止单元格。
将您的('SPAN', (0, 0), (-1, -1))更改为('SPAN', (0, 0), (4, 0))

  

SPAN,(sc,sr),(ec,er)表示sc-ec和c列中的单元格   行sr-er应该合并到具有内容的超级单元中   由单元格(sc,sr)确定。

如果我尝试用数学方法进行解释,即矩阵表示形式,它将是合并矩阵[0] [0]和矩阵[0] [4]。
我知道,这有点令人困惑。

相关问题