我目前正在使用 MS Access 生成报告,但我需要做的一些计算有些受限。
我正在考虑使用 Python 来运行报告,即每行数据一个报告,它采用列字段并将它们放在向下的文本框中,看起来像:
这在 Python 中如何实现?
最佳答案
这有点超出 Pandas,但您可以借助以下 Python 库从 Pandas DataFrame(使用 1.2.5 版测试)的每一行创建 PDF 报告:
首先,在report_template.html
中定义报告的结构和外观:
<html>
<head>
<style type="text/css">
html, body {
width: 500px;
font-size: 12px;
background: #fff;
padding: 0px;
}
#my-custom-table {
width: 500px;
border: 0;
margin-top: 20px;
}
#my-custom-table td {
padding: 5px 0px 1px 5px;
text-align: left;
}
</style>
</head>
<body>
<table cellspacing="0" border="0" style="width:500px; border:0; font-size: 14px;">
<tr>
<td style="text-align:left;">
<b><span>Title of the PDF report - Row {{ row_ix + 1 }}</span></b>
</td>
<td style="text-align:right;">
<b><span>{{ date }}</span></b>
</td>
</tr>
</table>
<table cellspacing="0" border="0" id="my-custom-table">
{% for variable_name, variable_value in row.iteritems() %}
{% if loop.index0 == 0 %}
<tr style="border-top: 1px solid black;
border-bottom: 1px solid black;
font-weight: bold;">
<td>Variable name</td>
<td>Variable value</td>
</tr>
{% else %}
<tr>
<td>{{ variable_name }}</td>
<td>{{ variable_value }}</td>
</tr>
{% endif %}
{% endfor %}
</table>
</body>
</html>
然后,运行这个 Python 3 代码,它通过 jinja2
将 DataFrame 的每一行转换为 HTML 字符串,然后通过 xhtml2pdf
将 HTML 转换为 PDF:
from datetime import date
import jinja2
import pandas as pd
from xhtml2pdf import pisa
df = pd.DataFrame(
data={
"Average Introducer Score": [9, 9.1, 9.2],
"Reviewer Scores": ["Academic: 6, 6, 6", "Something", "Content"],
"Average Academic Score": [5.7, 5.8, 5.9],
"Average User Score": [1.2, 1.3, 1.4],
"Applied for (RC)": [9.2, 9.3, 9.4],
"Applied for (FEC)": [5.5, 5.6, 5.7],
"Duration (Months)": [36, 37, 38],
}
)
for row_ix, row in df.iterrows():
# Pandas DataFrame to HTML
html = (
jinja2.Environment(loader=jinja2.FileSystemLoader(searchpath=""))
.get_template(name="report_template.html")
.render(
date=date.today().strftime("%d, %b %Y"),
row_ix=row_ix,
row=row,
)
)
# Convert HTML to PDF
with open("report_row_%s.pdf" % (row_ix + 1), "w+b") as out_pdf_file_handle:
pisa.CreatePDF(
# HTML to convert
src=html,
# File handle to receive the result
dest=out_pdf_file_handle,
)
对于Python代码中指定的DataFrame,会输出3个PDF。第一个 PDF 看起来像这样(转换为 PNG 以便能够在此处显示):
关于python - 是否可以使用 Python Pandas 构建报告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44001570/