python企微推送数据表格图片

from webot import WechatBot
from hdfs.client import InsecureClient
from io import StringIO
import pandas as pd
import numpy as np
from tqdm import tqdm
from hdfs import HdfsError
import os
import pandas as pd
import matplotlib.pyplot as plt  
plt.rcParams['font.sans-serif'] = ['SimHei']  # 指定默认字体 'SimHei'为黑体
plt.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题
import matplotlib.pyplot as plt
from pandas.plotting import table
 

#数据节点连接,数据中心基本只会在这两个节点之间切,复制粘贴即可  fr永恩
try:
    client = InsecureClient(url="http://nn2.ns1",user="admin")
    print('r1',client.list('/'))
except HdfsError as e:
    if "Operation category READ is not supported in state standby" in str(e):
        client = InsecureClient(url="http://nn1.ns12.",user="admin")
        print('r2',client.list('/'))
    else:
        print("其他 HdfsError 异常:", e)
 

names=['pdate','current_hour','sku','success_ordercnt','hb_success_ordercnt','success_membercnt','hb_success_membercnt','success_payamount','success_totalamount','cancel_ordercnt','cancel_membercnt']
hdfs_file="/ns-traffic/tmp/mdapp_sku_ontime_1214156_20240506"
df_data=pd.DataFrame(columns=names)
for i in tqdm(client.list(hdfs_path=hdfs_file)):
    file_path=hdfs_file+'/'+i
    with client.read(file_path,encoding='utf-8', delimiter=' ') as reader:
        tmp=pd.read_csv(StringIO(' '.join(reader)), sep='x01', names=names)
    df_data=pd.concat([df_data,tmp],axis=0,ignore_index=True)
print(df_data)

def write_data_to_excel(df, file_path):
    """
    Write a DataFrame to an Excel file.
    """
    df.to_excel(file_path, index=False)

   
  
def save_df_as_image(df, img_path):
    """
    Save a DataFrame as an image.
    """
    fig, ax = plt.subplots(figsize=(15,4)) # set size frame表示创建一个宽12英寸、高6英寸的图形
    ax.xaxis.set_visible(False)  # hide the x axis
    ax.yaxis.set_visible(False)  # hide the y axis
    ax.set_frame_on(False)  # no visible frame
    tabla = table(ax, df, loc='center', cellLoc = 'center')  # where df is your data frame
    tabla.auto_set_font_size(False) # Activate set fontsize manually
    tabla.set_fontsize(10) # if ++fontsize is necessary ++colWidths
    tabla.scale(1.2, 1.2) # Table size 
    plt.savefig(img_path)


# 定义新的列名
new_column_names = {"pdate": "日期","current_hour":"时刻",  "sku": "业务线",
                    "success_ordercnt": "成功消费订单数", "hb_success_ordercnt": "成功消费订单环比",
"success_membercnt": "成功消费用户数", "hb_success_membercnt": "成功消费人数环比", 
                    "success_payamount": "成功消费实付金额","success_totalamount": "成功消费订单金额", 
                  "cancel_ordercnt": "取消订单数", "cancel_membercnt": "取消用户数"}
#names=['pdate','sku','success_membercnt','hb_success_membercnt','success_ordercnt','hb_success_ordercnt','success_payamount','success_totalamount','cancel_membercnt','cancel_ordercnt']
df_data.rename(columns=new_column_names, inplace=True)
df =df_data

# Use the above functions
write_data_to_excel(df, "test.xlsx")
save_df_as_image(df, "table.png")


# 发送图片
image_path = os.path.abspath('table.png')
# 注意webhook_url这里替换为自己申请的机器人webhook
webhook_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/s" #注意换成自己的机器人hook地址
bot = WechatBot(webhook_url)
bot.send_picture(image_path)
 

关注公众号「水沐教育科技」,在手机上阅读所有教程,随时随地都能学习。内含一款搜索神器,免费下载全网书籍和视频。

公众号二维码
微信扫码关注公众号

微信交流群 关注微信公众号,加入官方交流群。内含一款搜索神器,免费下载全网书籍和视频。