通过Python写html报表
时间: 2023-07-08 18:42:12 浏览: 55
可以使用Python的第三方库来生成HTML报表,其中比较常用的是pandas和jinja2。
1. 使用pandas生成HTML表格
```python
import pandas as pd
# 构造数据
data = {'name': ['张三', '李四', '王五'], 'age': [18, 20, 22], 'gender': ['男', '女', '男']}
# 将数据转为DataFrame格式
df = pd.DataFrame(data)
# 生成HTML表格
html_table = df.to_html(classes='table', index=False)
print(html_table)
```
2. 使用jinja2模板生成HTML报表
```python
from jinja2 import Environment, FileSystemLoader
# 构造数据
data = {'name': ['张三', '李四', '王五'], 'age': [18, 20, 22], 'gender': ['男', '女', '男']}
# 将数据传入jinja2模板
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template('report_template.html')
html_report = template.render(data=data)
print(html_report)
```
需要注意的是,这里使用了jinja2模板,需要自行编写HTML模板文件`report_template.html`,将数据通过占位符(如`{{ data.name }}`)插入到模板中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)