How to Repeat Table Column Headings over Page Breaks in PDF output from ReportLab

前端 未结 5 1843
死守一世寂寞
死守一世寂寞 2021-02-07 06:42

I\'m using ReportLab to write tables in PDF documents and am very pleased with the results (despite not having a total grasp on flowables just yet).

However, I have not

5条回答
  •  死守一世寂寞
    2021-02-07 07:17

    Use the repeatRows=1 when you create the Table...

    from reportlab.platypus import Table 
    Table(data,repeatRows=1)
    

    I always like to have something you can cut & paste into a .py file to run and test. So here it is...

    import os
    import pandas as pd
    import numpy as np
    import reportlab.platypus 
    import reportlab.lib.styles
    from reportlab.lib import colors
    from reportlab.lib.units import mm
    from reportlab.lib.pagesizes import letter, landscape
    
    reportoutputfilepath = os.path.join('.\\test.pdf')
    
    pdf_file = reportlab.platypus.SimpleDocTemplate(
                                reportoutputfilepath,
                                pagesize=landscape(letter),
                                rightMargin=10,
                                leftMargin=10,
                                topMargin=38,
                                bottomMargin=23
                        )
    ts_tables = [
             ('ALIGN', (4,0), (-1,-1), 'RIGHT'),
             ('LINEBELOW', (0,0), (-1,0), 1, colors.purple),
             ('FONT', (0,0), (-1,0), 'Times-Bold'),
             ('LINEABOVE', (0,-1), (-1,-1), 1, colors.purple),
             ('FONT', (0,-1), (-1,-1), 'Times-Bold'),
             ('BACKGROUND',(1,1),(-2,-2),colors.white),
             ('TEXTCOLOR',(0,0),(1,-1),colors.black),
             ('FONTSIZE', (0,0),(-1,-1), 8), 
             ]
    
    df = pd.DataFrame(np.random.randint(0,1000,size=(1000, 4)), columns=list('ABCD'))
    lista = [df.columns[:,].values.astype(str).tolist()] + df.values.tolist()
    
    #Here is where you put repeatRows=1
    table = reportlab.platypus.Table(lista, colWidths=(20*mm, 20*mm, 20*mm, 20*mm),repeatRows=1)
    table_style = reportlab.platypus.TableStyle(ts_tables)
    table.setStyle(table_style)
    elements = []
    elements.append(table)
    
    # Build the PDF
    pdf_file.build(elements)
    print reportoutputfilepath
    

提交回复
热议问题