Search code examples
pythonpandasreportlab

How to convert a pandas DataFrame into a table in the reportlab module?


I have the DataFrame below:

enter image description here

The issue is that when I try to make a table out of summary_debit which is a DataFrame, I will get the following error: ValueError: <Table@0x2231B045208 unknown rows x unknown cols>... invalid data type

from reportlab.pdfgen import canvas
from reportlab.platypus import *
from reportlab.lib import colors

colwidths = 50
GRID_STYLE = TableStyle(
            [('GRID', (0, 0), (-1, -1), 0.25, colors.pink),
            ('ALIGN', (1, 0), (-1, -1), 'RIGHT')])

t1 = Table(summary_debit)

Solution

  • I built a sample for your DataFrame image, but you can extends that.

    After running code I got a proper pdf.

    I hope this code help you.

    from reportlab.pdfgen import canvas
    from reportlab.platypus import *
    from reportlab.lib import colors
    from reportlab.lib.pagesizes import letter
    import pandas as pd
    import numpy as np
    
    data = {'Account Name': ['ACCOUNT PAYABLE', 'PAGIBIG LOAN PAYABLE','PREPAID TAX']
                ,'': [-0.1, -0.2,-0.3]}
    summary_debit = pd.DataFrame(data=data)
    
    colwidths = 50
    GRID_STYLE = TableStyle(
                [('GRID', (0, 0), (-1, -1), 0.25, colors.pink),
                ('ALIGN', (1, 0), (-1, -1), 'RIGHT')])
    
    #t1 = Table([summary_debit.iloc[:,1].tolist(),summary_debit.iloc[:,0].tolist()]);
    t1 = Table(np.array(summary_debit).tolist());
    doc = SimpleDocTemplate("table.pdf", pagesize=letter)
    element = []
    element.append(t1)
    doc.build(element)
    

    PDF image export

    pdf export