怎样用 Python 脚本读取 Excel 并自动更新 SVG 图表,实现日报无人值守?
解读
面试官想确认三件事:
- 你是否理解 SVG 只是纯文本 XML,可被 Python 直接读写,无需打开 Inkscape;
- 你是否能把 Excel 数据自动、可靠、定时地喂给 SVG 模板,并保证中文、颜色、单位、精度都不出错;
- 你是否具备把整套流程做成“无人值守”的工程化能力:日志、异常、回滚、CI、Windows 计划任务或 Linux systemd 都要闭环。
国内公司日报通常早上 8:30 前推送到企业微信或邮件,脚本必须在前一晚跑完;因此脚本失败必须能自动重试并告警,否则业务方会第一时间投诉。
知识点
- SVG 结构:根节点 svg 下的 g、text、tspan、rect、path 等元素;id 与 class 属性是替换锚点。
- Excel 读取:pandas 读 .xlsx,openpyxl 可保留单元格样式;注意中文编码、日期列 dtype 与空值处理。
- 模板化:在 SVG 里用 {{placeholder}} 或自定义 data-field 属性占位,避免硬编码坐标。
- 渲染策略:
- 纯文本替换:适合标题、数值;
- 属性替换:x、y、width、height、fill、stroke;
- 路径重写:用 path 的 d 属性画动态折线或饼图,需把数据归一化到 SVG 视口坐标系。
- 中文与字体:确保 SVG 内嵌 @font-face 或指定系统已安装字体,防止在服务器端生成图片时乱码。
- 精度与单位:Excel 里可能是万元、百分比,脚本要统一换算成 px 或 mm;SVG 视口用 viewBox 做响应式。
- 定时调度:Windows 用“任务计划程序”+.bat 调用 Python;Linux 用 systemd timer 或 crond;失败回退策略:重试 3 次后发钉钉机器人告警。
- 版本与回滚:每次生成新 SVG 带时间戳,软链 latest.svg 给前端;出错可秒级回滚。
- 扩展:若日报还需 PNG 预览,可用 Inkscape 无头模式:
inkscape --export-type=png --export-filename=out.png latest.svg,但 CI 环境需安装 Inkscape 并配置 DISPLAY=:99 虚拟帧缓冲。 - 合规:SVG 里不要嵌入敏感明文数据;服务器文件权限 640,日志脱敏。
答案
给出一个最小可落地的生产级方案,可直接讲给面试官:
- 目录结构
project/
├─ config.yaml # 数据源、阈值、字体路径
├─ template.svg # 带占位符的矢量模板
├─ daily.py # 主脚本
├─ log/ # 按日期滚动日志
└─ out/ # 生成的 svg/png
- config.yaml 示例
excel_path: "/data/report.xlsx"
sheet_name: "日报"
svg_template: "template.svg"
output_dir: "out"
font_family: "SourceHanSansSC-Regular"
warn_threshold: 0.05 # 数据波动超过 5% 告警
- template.svg 片段
<text id="sales_today" x="100" y="150" font-size="36" fill="#333">
{{sales_today}}
</text>
<rect id="bar" x="100" y="200" width="{{bar_width}}" height="30" fill="#1890ff"/>
- daily.py 核心代码
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pandas as pd
import xml.etree.ElementTree as ET
from datetime import datetime
import os, shutil, logging, yaml, sys
def init_log():
logfile = f"log/{datetime.now():%Y%m%d}.log"
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)s %(message)s',
handlers=[logging.FileHandler(logfile, encoding='utf-8'),
logging.StreamHandler()])
def load_excel(cfg):
df = pd.read_excel(cfg['excel_path'], sheet_name=cfg['sheet_name'], dtype={'销售额': float})
if df.empty:
raise ValueError("Excel 无数据")
latest = df.iloc[-1] # 取最后一行
return {
'sales_today': f"{latest['销售额']/1e4:.1f}万",
'bar_width': max(10, int(latest['销售额']/1e3)) # 简单映射
}
def render_svg(data, cfg):
tree = ET.parse(cfg['svg_template'])
root = tree.getroot()
# 替换 text
for node in root.iter():
if node.tag.endswith('text') and node.attrib.get('id') in data:
node.text = data[node.attrib['id']]
# 替换属性
for key, val in node.attrib.items():
if val.startswith('{{') and val.endswith('}}'):
placeholder = val[2:-2]
node.set(key, str(data.get(placeholder, 0)))
outfile = f"{cfg['output_dir']}/report_{datetime.now():%Y%m%d_%H%M}.svg"
tree.write(outfile, encoding='utf-8', xml_declaration=True)
latest = f"{cfg['output_dir']}/latest.svg"
shutil.copy(outfile, latest)
return latest
def main():
init_log()
try:
cfg = yaml.safe_load(open('config.yaml', encoding='utf-8'))
data = load_excel(cfg)
svg_path = render_svg(data, cfg)
logging.info(f"成功生成 {svg_path}")
# 可选:转 PNG
# os.system(f'inkscape --export-type=png --export-filename={svg_path}.png {svg_path}')
except Exception as e:
logging.error("日报生成失败", exc_info=True)
# 发钉钉告警
# requests.post(dingding_url, json={"msgtype":"text","text":{"content":"日报失败"}})
sys.exit(2)
if __name__ == '__main__':
main()
-
无人值守
Windows:任务计划程序,每天 6:00 执行python daily.py,执行目录设到 project 根,日志重定向到 log。
Linux:/etc/systemd/system/daily-svg.service + daily-svg.timer,OnCalendar=--* 06:00:00,失败自动重启 3 次,重启间隔 5 分钟;仍失败则通过 ExecStopPost 调用钉钉脚本告警。 -
回滚与监控
out 目录保留最近 30 份 SVG,latest.svg 始终指向最新;监控脚本每 5 分钟检测 latest.svg 时间戳,若超过 25 小时未更新则报警。
拓展思考
- 如果日报图表需要复合饼图、堆叠柱状图,手写 path 太繁琐,可引入 pygal、matplotlib 生成 SVG 字符串,再嵌入模板,这样既能利用成熟图表库,又保持矢量无损。
- 当 Excel 数据量上升到百万行,pandas 读取慢,可以改用 openpyxl 的只读模式或把数据先落到 SQLite,凌晨由 ETL 汇总,Python 脚本只读结果表,降低 IO 压力。
- 若公司要求多端展示(大屏、小程序、邮件),可再增加一步“SVG 压缩 + 雪碧图”优化,或使用 svg-sprite-loader 把图标合并,提高前端渲染性能。
- 安全层面,SVG 支持 JavaScript,若日报需上 Web,必须清洗 script 标签,防止 XSS;服务器端生成完建议再走一遍 svg-sanitizer。
- 长期维护:把模板、脚本、配置全部纳入 GitLab CI,Merge Request 触发单元测试(pytest 检查占位符是否都被替换),通过后才允许合并到主分支,实现“图表即代码”。