如何在 reportlab 模块中将 pandas DataFrame 转换为 table?

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

我有下面的 DataFrame:

问题是,当我尝试从 summary_debit(即 DataFrame 中创建 table 时,我会收到以下错误: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)

我为您的 DataFrame 图像构建了一个示例,但您可以扩展它。

在 运行 代码之后我得到了一个合适的 pdf。

希望这段代码对您有所帮助。

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 图片导出