话不多说,有图有源码
1.实现效果:
按季度统计
按月度统计:
2.实现源码:
2.1)test_pandashtml.py
from flask import Flask, render_template
import pandas as pd
app = Flask(__name__)
# 自定义千分位格式化函数
def format_thousands(x):
return f'{x:,.2f}'
@app.route('/')
def show_dataframe():
path = r'F:\test_data\年度销售数据\xxx年度销售数据.xlsx'
data = pd.read_excel(path, engine='openpyxl')
data['报审日期'] = pd.to_datetime(data['报审日期'])
year = data['报审日期'].dt.year
quarter = data['报审日期'].dt.quarter
month = data['报审日期'].dt.month
# print(f"{type(month)},{month}")
data2 = pd.pivot_table(data, index=['事业部','办事处部门'], values='合同金额', columns=month,
aggfunc=sum) # ,'办事处部门',fill_value='无'
# -------数值千分位格式化
data2 = data2.applymap(format_thousands) # .fillna(value=0, inplace=True)
print(data2)
# 将DataFrame转换为HTML
html = data2.to_html() #index=False
return render_template('test.html', table=html)
if __name__ == '__main__':
app.run(debug=True)
2.2)html页面test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
table {
border-collapse: collapse;
width: 100%;
text-align: left;
font-family: Arial, sans-serif;
font-size: 14px;
}
td, th {
border: 1px solid #ddd;
padding: 8px;
}
th {
background-color: #f2f2f2;
color: #333;
}
tr:nth-child(even) {
background-color: #f9f9f9;
}
</style>
</head>
<body>
<div>
{{ table|safe }}
</div>
</body>
</html>
3.注意细节:
3.1)遇到不规范的日期格式,会报错怎么办
3.2)显示输出的数据格式为千分位加保留两位小数的方法,使用applymap
就到这吧,对你有用给个赞