写一个python脚本,访问sql数据库,执行sql语句,查询在指定日期内每24小时的结果,并将结果按照不同日期输出到一个excel文件中。结果值大于20且小于30的标识绿色,结果值小于20且大于10的标识黄色,小于10的标识灰色。
时间: 2023-02-21 18:21:23 浏览: 178
以下是一个示例代码:
```python
import pymysql
import pandas as pd
from openpyxl import Workbook
from openpyxl.styles import PatternFill
# 连接数据库
conn = pymysql.connect(host='host', port=3306, user='user', password='password', database='database')
cursor = conn.cursor()
# 查询数据
start_date = "2023-01-01"
end_date = "2023-01-31"
sql = f"SELECT date, result FROM table WHERE date BETWEEN '{start_date}' AND '{end_date}'"
cursor.execute(sql)
data = cursor.fetchall()
# 转换为DataFrame
df = pd.DataFrame(data, columns=["date", "result"])
# 设置颜色
green_fill = PatternFill(start_color="00FF00", end_color="00FF00", fill_type="solid")
yellow_fill = PatternFill(start_color="FFFF00", end_color="FFFF00", fill_type="solid")
gray_fill = PatternFill(start_color="808080", end_color="808080", fill_type="solid")
for i in range(len(df)):
if df.loc[i, "result"] >= 20 and df.loc[i, "result"] < 30:
df.loc[i, "color"] = green_fill
elif df.loc[i, "result"] >= 10 and df.loc[i, "result"] < 20:
df.loc[i, "color"] = yellow_fill
else:
df.loc[i, "color"] = gray_fill
# 创建Excel工作簿并保存
book = Workbook()
writer = pd.ExcelWriter("result.xlsx", engine='openpyxl')
writer.book = book
for date, group in df.groupby(by='date'):
group.to_excel(writer, sheet_name=date, index=False)
sheet = writer.sheets[date]
for row in range(len(group)):
for col in range(2):
sheet.cell(row+1, col+1).fill = group.loc[row, "color"]
writer.save()
# 关闭数据库连接
cursor.close()
conn.close()
```
需要注意的是,这份代码需要安装pandas和openpyxl库,你可以使用以下命令安装:
```
pip install pandas
pip install openpyxl
```
这份代码仅作为示例,你需
阅读全文