本文完整展示如何使用 Tornado 異步 Web 框架,結合 xlrd 讀取 Excel 考勤記錄、MongoDB 儲存資料、ECharts 生成圖表,打造一套值班打卡數據視覺化系統。涵蓋資料清洗、跨月跨年邏輯、值班規則匹配、RESTful API 設計等實戰技巧。
pip install xlrd)每日 6 個班次(08:00-22:00),每人每天最多一班。需上下班雙打卡,缺一視為未值班。設計三個 Collection:
user:{id, name, dept}record:{id, y, m, d, check} 打卡記錄duty:{id(星期), list[人員ID], user_id: {start_time, end_time}} 值班排程指紋機匯出的 Excel 第 3 個 sheet 為考勤記錄:

關鍵邏輯:遍歷日期時若 d < lastday 表示換月;若 m1==12 and m2==1 則年份 +1。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os.path, tornado.auth, tornado.escape, tornado.httpserver
import tornado.ioloop, tornado.options, tornado.web
from tornado.options import define, options
import pymongo, time, datetime, xlrd
define("port", default=8007, help="run on the given port", type=int)
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", MainHandler),
(r"/read", ReadHandler),
(r"/day", DayHandler),
]
settings = dict(
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
debug=True,
)
conn = pymongo.Connection("localhost", 27017)
self.db = conn["kaoqin"]
tornado.web.Application.__init__(self, handlers, **settings)
class ReadHandler(tornado.web.RequestHandler):
def get(self):
coll_record = self.application.db.record
coll_user = self.application.db.user
table = xlrd.open_workbook('/Users/ant/Webdev/python/excel/data.xls')
sheet = table.sheet_by_index(2)
# 讀取月份範圍、年份、日期行...
row3 = sheet.row_values(2)
m1 = int(row3[2][5:7]); m2 = int(row3[2][18:20])
y = int(row3[2][0:4])
m = m1
row4 = sheet.row_values(3)
lastday = row4[0]
for d in row4:
if d < lastday: m = m2
if m1 == 12 and m2 == 1: y = y + 1
# 遍歷用戶行...
for n in range(3, sheet.nrows/2+1):
row_1 = sheet.row_values(n*2-2)
u_id = row_1[2]; u_name = row_1[10]; u_dept = row_1[20]
user = coll_user.find_one({"id": u_id})
if not user:
user = dict()
# ... 建立用戶與寫入打卡記錄邏輯
後端輸出 JSON,前端 ECharts 直接渲染。完整原始碼註解詳見專案源碼。
Tornado 單執行緒異步模型適合 I/O 密集型場景。生產環境建議:
xheaders=True 取得真實客戶 IP