Files
37duAutomation/tools/sheet_print.py
T
puddy 2eda11396d chore(tools): 新增打印/PDF/表格工具与 OA→ERP 单点登录脚本
- tools/printer_probe.py:打印机协议非破坏性探测(端口/IPP 能力/LPD 队列,绝不提交作业)
- tools/printer_client.py:IPP 直连打印(info / validate 干跑 / print 需显式 --yes)
- tools/doc2pdf.py:网页 / HTML / Excel 指定区域转 PDF,产物可直接交给 printer_client
- tools/sheet_print.py:Excel·WPS 表格按列过滤排版后分页打印
- tools/xq0012_payapply_pdf.py:XQ0012 套打 PDF 本地预览工具
- workflows/share/erp_sso_login.py:读 OA 登录态换 ERP 会话(新版/旧版,纯接口无浏览器)
- workflows/README.md 新增 4.9 节说明
2026-11-16 11:28:01 +08:00

482 lines
20 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""读取 Excel/WPS 工作表 → 按列过滤 → 生成矢量 PDF(可选直接送打印机)。
解决的是"WPS 固定区域打印"这类需求:不依赖 WPS 的导出(本机 12.1 版导出 PDF
有排版缩放 bug),改为自己读单元格值、自己排版、自己出 PDF。
过滤规则(默认,可关)
--------------------
丢掉:空值 / 0 / Excel 错误值(#REF! #N/A #VALUE! ...) / 文本"错误"
用法
----
# 只看不打印
python tools/sheet_print.py --file "D:\\x.xlsx" --sheet 单子传递打印 \
--col "FRECTUNIT#Name" --out tools/out/out.pdf
# 渲染并真机打印
python tools/sheet_print.py --file "D:\\x.xlsx" --sheet 单子传递打印 \
--col "FRECTUNIT#Name" --print-to "fe80::9eae:d3ff:fef8:17ea%8" --yes
"""
from __future__ import annotations
import argparse
import datetime as _dt
import math
import re
import sys
from pathlib import Path
import fitz # PyMuPDF
import openpyxl
FONT_R = r"C:\Windows\Fonts\msyh.ttc"
FONT_B = r"C:\Windows\Fonts\msyhbd.ttc"
A4_W, A4_H = 595.28, 841.89
ERR_RE = re.compile(r"^#(REF!|N/A|VALUE!|DIV/0!|NAME\?|NULL!|NUM!|GETTING_DATA)$", re.I)
ERR_WORDS = {"错误", "error", "#error"}
# --------------------------------------------------------------------------- #
# 取值与过滤
# --------------------------------------------------------------------------- #
def fmt_value(v) -> str:
"""把单元格值转成可打印文本。"""
if v is None:
return ""
if isinstance(v, _dt.datetime):
return v.strftime("%Y-%m-%d") if (v.hour, v.minute) == (0, 0) else v.strftime("%Y-%m-%d %H:%M")
if isinstance(v, _dt.date):
return v.strftime("%Y-%m-%d")
if isinstance(v, bool):
return "是" if v else "否"
if isinstance(v, float):
return str(int(v)) if v.is_integer() else f"{v:g}"
return str(v)
def is_bad(v) -> bool:
"""空 / 0 / 错误值 / 文本"错误" → 丢弃。"""
if v is None:
return True
if isinstance(v, str):
s = v.strip()
if s == "" or s == "0" or ERR_RE.match(s) or s.lower() in ERR_WORDS:
return True
return False
if isinstance(v, (int, float)) and not isinstance(v, bool):
return v == 0
return False
def find_column(ws, key: str, header_row: int) -> int:
"""按字段名(第1行)或中文标题(header_row)或列字母定位列号。"""
if re.fullmatch(r"[A-Za-z]{1,3}", key):
return openpyxl.utils.column_index_from_string(key.upper())
for r in (1, header_row):
for c in range(1, ws.max_column + 1):
v = ws.cell(row=r, column=c).value
if v is not None and str(v).strip() == key:
return c
# 宽松匹配
for r in (1, header_row):
for c in range(1, ws.max_column + 1):
v = ws.cell(row=r, column=c).value
if v is not None and key.lower() in str(v).lower():
return c
raise ValueError(f"找不到列 {key!r}")
# --------------------------------------------------------------------------- #
# 排版
# --------------------------------------------------------------------------- #
class TablePDF:
def __init__(self, title: str = "", fontsize: float = 9.0,
margin: float = 42.0, landscape: bool = False):
self.font_r = fitz.Font(fontfile=FONT_R)
self.font_b = fitz.Font(fontfile=FONT_B)
self.title = title
self.fs = fontsize
self.margin = margin
self.doc = fitz.open()
self.W, self.H = (A4_H, A4_W) if landscape else (A4_W, A4_H)
self.page = None
self.y = 0.0
self.page_no = 0
self.cont = True # 第 2 页起页脚加"(续)"
self._new_page()
# --- 页面 ---
def _new_page(self):
self.page = self.doc.new_page(width=self.W, height=self.H)
self.page.insert_font(fontname="cjk", fontfile=FONT_R)
self.page.insert_font(fontname="cjkb", fontfile=FONT_B)
self.page_no += 1
self.y = self.margin
if self.title:
self.page.insert_text((self.margin, self.y + 14), self.title,
fontname="cjkb", fontsize=self.fs + 5)
self.y += 34
def _measure(self, text: str, bold: bool = False, size: float | None = None) -> float:
f = self.font_b if bold else self.font_r
return f.text_length(text, fontsize=size or self.fs)
# 收尾标点不允许出现在行首(中文排版禁则)
CLOSERS = "))】]},,。.、;;::!!??%"
def _wrap(self, text: str, width: float, bold: bool = False,
size: float | None = None) -> list[str]:
"""按实际字形宽度折行(中文可任意断行,英文尽量不断在单词中间)。"""
if not text:
return [""]
size = size or self.fs
lines, cur = [], ""
for ch in text:
if self._measure(cur + ch, bold, size) <= width:
cur += ch
continue
if cur and ch in self.CLOSERS:
# 收尾标点挂在行尾(允许 1 字溢出),避免 "(序号" 换行后只剩 ")"
cur += ch
lines.append(cur)
cur = ""
continue
if cur and ch not in " ":
# 英文单词尽量不断开
m = re.search(r"[A-Za-z0-9_#%\.\-]+$", cur)
if m and ch.isalnum():
keep = cur[:m.start()]
if keep:
lines.append(keep)
cur = cur[m.start():] + ch
continue
lines.append(cur)
cur = "" if ch == " " else ch
lines.append(cur)
return lines or [""]
# --- 表格 ---
def table(self, header_rows: list[list[str]], rows: list[list[str]],
weights: list[float] | None = None, min_widths: list[float] | None = None,
total_row: list[str] | None = None):
"""header_rows: 多行表头,例如 [英文字段行, 中文标题行]。
total_row: 末尾合计行(加粗 + 双线上边框)。"""
avail = self.W - 2 * self.margin
n = len(header_rows[0])
fs = self.fs
# 英文字段行不一定放得下,自动缩字号直到整行放得下(不低于 6pt)
fs_key = max(6.0, fs * 0.86)
# 单列宽度上限:防止某个超长单元格把其它列挤成竖排单字
cap = max(120.0, avail / n * 2.2)
floor = max(34.0, min(56.0, avail / n * 0.55))
def natural_widths(key_size: float) -> list[float]:
out = []
for i in range(n):
w = 0.0
for bi, hr in enumerate(header_rows):
sz = key_size if bi == 0 else fs
w = max(w, self._measure(hr[i], bold=True, size=sz) + 12)
for r in rows[:400]:
w = max(w, self._measure(r[i], size=fs) + 12)
out.append(min(w, cap))
return out
def fit_to_avail(nat: list[float]) -> list[float]:
"""按比例铺满可用宽度,同时保证每列不小于 floor。"""
w = list(nat)
tot = sum(w) or 1.0
w = [x * avail / tot for x in w]
for _ in range(5):
low = [i for i, x in enumerate(w) if x < floor]
if not low or len(low) == n:
if len(low) == n:
return [avail / n] * n
break
rest = avail - floor * len(low)
high = [i for i in range(n) if i not in low]
htot = sum(w[i] for i in high) or 1.0
for i in high:
w[i] = w[i] * rest / htot
for i in low:
w[i] = floor
if all(w[i] >= floor for i in high):
break
return w
nat = natural_widths(fs_key)
while sum(nat) > avail and fs_key > 6.0:
fs_key *= 0.94
nat = natural_widths(fs_key)
widths = fit_to_avail(nat)
if min_widths:
widths = [max(w, min_widths[i]) for i, w in enumerate(widths)]
k = avail / sum(widths)
widths = [w * k for w in widths]
lh = fs * 1.45
pad = 3.0
bottom_limit = self.H - self.margin - 14
def header_bands():
"""返回 [(该行折行结果, 该行高度, 该行字号), ...]。"""
out = []
for bi, hr in enumerate(header_rows):
sz = fs_key if bi == 0 else fs
wrapped = [self._wrap(hr[i], widths[i] - 2 * pad, bold=True, size=sz)
for i in range(n)]
out.append((wrapped, max(len(x) for x in wrapped) * sz * 1.45 + 2 * pad, sz))
return out
bands = header_bands()
header_h = sum(h for _, h, _ in bands)
# 数字列右对齐(金额、序号等),文本列左对齐
num_re = re.compile(r"^-?[\d,]+(\.\d+)?%?$")
aligns: list[str] = []
for i in range(n):
vals = [r[i].strip() for r in rows if r[i].strip()]
aligns.append("right" if vals and all(num_re.match(v) for v in vals) else "left")
# 每个数据行先算好折行与行高;超过一整页的极端单元格做截断,避免死循环
# 注意:每页都重绘标题,可用高度要扣掉标题占位
title_h = 34.0 if self.title else 0.0
avail_for_rows = bottom_limit - (self.margin + title_h) - header_h
max_cell_lines = max(1, int(avail_for_rows // lh) - 1)
prepared: list[tuple[list[list[str]], float]] = []
for row in rows:
cells = [self._wrap(row[i], widths[i] - 2 * pad) for i in range(n)]
over = [j for j in range(n) if len(cells[j]) > max_cell_lines]
if over:
cells = [c[:max_cell_lines] for c in cells]
for j in over: # 只给真正被截断的单元格加省略号
cells[j][-1] += "…"
h = max(len(c) for c in cells) * lh + 2 * pad
prepared.append((cells, h))
# 记录每页表格区域 [(page, top, bottom)],用于最后统画竖线和外框
regions: list[list] = []
open_region: list[list | None] = [None]
def start_region():
if open_region[0] is None:
# 存页号而不是 Page 对象:新增页面后旧 Page 引用会失效
open_region[0] = [self.page.number, self.y, None]
def close_region():
if open_region[0] is not None:
open_region[0][2] = self.y
regions.append(open_region[0])
open_region[0] = None
def page_break():
close_region()
self._new_page()
def draw_header():
if self.y + header_h > bottom_limit:
page_break()
start_region()
y0 = self.y
for bi, (wrapped, h, sz) in enumerate(bands):
# 英文字段行浅灰,中文标题行更深一点的灰
fill = (0.87, 0.87, 0.87) if bi == 0 else (0.94, 0.94, 0.94)
self.page.draw_rect(fitz.Rect(self.margin, y0, self.margin + avail, y0 + h),
color=None, fill=fill)
x = self.margin
for i in range(n):
ty = y0 + pad + sz
for ln in wrapped[i]:
self.page.insert_text((x + pad, ty), ln, fontname="cjkb", fontsize=sz)
ty += sz * 1.45
x += widths[i]
y0 += h
self.page.draw_line(fitz.Point(self.margin, y0),
fitz.Point(self.margin + avail, y0),
color=(0, 0, 0), width=0.6)
self.y = y0
def draw_row(cells: list[list[str]], h: float, bold: bool = False):
x = self.margin
for i in range(n):
ty = self.y + pad + fs
for ln in cells[i]:
tx = x + pad
if aligns[i] == "right":
tx = x + widths[i] - pad - self._measure(ln, bold, fs)
self.page.insert_text((tx, ty), ln,
fontname="cjkb" if bold else "cjk", fontsize=fs)
ty += lh
x += widths[i]
self.page.draw_line(fitz.Point(self.margin, self.y + h),
fitz.Point(self.margin + avail, self.y + h),
color=(0, 0, 0), width=1.2 if bold else 0.6)
self.y += h
draw_header()
for ri, (cells, h) in enumerate(prepared):
if self.y + h > bottom_limit:
page_break()
draw_header()
if ri % 2 == 1:
self.page.draw_rect(fitz.Rect(self.margin, self.y, self.margin + avail, self.y + h),
color=None, fill=(0.965, 0.965, 0.965))
draw_row(cells, h)
# 合计行:加粗 + 粗上边框,尽量跟最后一行同页
if total_row:
tcells = [self._wrap(total_row[i], widths[i] - 2 * pad, bold=True) for i in range(n)]
th = max(len(c) for c in tcells) * lh + 2 * pad
if self.y + th > bottom_limit:
page_break()
draw_header()
self.page.draw_rect(fitz.Rect(self.margin, self.y, self.margin + avail, self.y + th),
color=None, fill=(0.90, 0.90, 0.90))
draw_row(tcells, th, bold=True)
close_region()
# 每页分别补竖线与外框(分页时每页都要有完整边框)
for pno, top, bottom in regions:
pg = self.doc[pno]
x = self.margin
for i in range(n - 1):
x += widths[i]
pg.draw_line(fitz.Point(x, top), fitz.Point(x, bottom),
color=(0, 0, 0), width=0.6)
pg.draw_rect(fitz.Rect(self.margin, top, self.margin + avail, bottom),
color=(0, 0, 0), width=0.8)
def footer(self, text: str):
for i, p in enumerate(self.doc):
t = text.replace("{page}", str(i + 1)).replace("{total}", str(len(self.doc)))
if self.cont and i > 0:
t = "(续)" + t
p.insert_text((self.W / 2 - self._measure(t) / 2, self.H - 22),
t, fontname="cjk", fontsize=8, color=(0.35, 0.35, 0.35))
def save(self, path: str) -> str:
p = Path(path)
p.parent.mkdir(parents=True, exist_ok=True)
try:
self.doc.subset_fonts() # 只嵌入用到的字形,否则整份 ttc 一起进去(几十 MB)
except Exception:
pass
self.doc.save(str(p), garbage=4, deflate=True)
self.doc.close()
return str(p)
# --------------------------------------------------------------------------- #
# 主流程
# --------------------------------------------------------------------------- #
def build_pdf(src: str, sheet: str | None, col: str, header_row: int,
title: str, out: str, drop_bad: bool = True,
landscape: bool = False, fontsize: float = 9.0,
key_row: int | None = 1, with_total: bool = False) -> tuple[str, int]:
wb = openpyxl.load_workbook(src, data_only=True)
ws = wb[sheet] if sheet else wb.active
ci = find_column(ws, col, header_row)
# 表头行:第 1 行是英文字段名(如 FRECTUNIT#Name),第 2 行是中文标题
hr_list = sorted({r for r in (key_row, header_row) if r and r >= 1})
header_rows: list[list[str]] = []
for r in hr_list:
line = []
for c in range(1, ws.max_column + 1):
v = fmt_value(ws.cell(row=r, column=c).value)
line.append(v if v.strip() else f"列{openpyxl.utils.get_column_letter(c)}")
header_rows.append(line)
first_data = max(hr_list) + 1
rows = []
for r in range(first_data, ws.max_row + 1):
key = ws.cell(row=r, column=ci).value
if drop_bad and is_bad(key):
continue
vals = [fmt_value(ws.cell(row=r, column=c).value) for c in range(1, ws.max_column + 1)]
if not any(v.strip() for v in vals):
continue
rows.append(vals)
wb.close()
# 合计行:对每一列,若所有非空值都是数字则求和
total_row = None
if with_total and rows:
ncol = len(header_rows[0])
total_row = ["合计"] + [""] * (ncol - 1)
for i in range(1, ncol):
nums, ok = [], True
for r in rows:
sv = r[i].strip().replace(",", "")
if sv == "":
continue
try:
nums.append(float(sv))
except ValueError:
ok = False
break
if ok and nums:
s = sum(nums)
has_dec = any("." in r[i] for r in rows)
total_row[i] = f"{s:,.2f}" if has_dec else f"{int(round(s)):,}"
pdf = TablePDF(title=title, fontsize=fontsize, landscape=landscape)
pdf.table(header_rows, rows, total_row=total_row)
pdf.footer(f"共 {len(rows)} 行 · 第 {{page}} / {{total}} 页")
path = pdf.save(out)
return path, len(rows)
def main() -> int:
ap = argparse.ArgumentParser(description="Excel 工作表 → 过滤 → 矢量 PDF / 打印")
ap.add_argument("--file", required=True)
ap.add_argument("--sheet", default=None)
ap.add_argument("--col", required=True, help="过滤列:字段名(如 FRECTUNIT#Name) 或列字母")
ap.add_argument("--header-row", type=int, default=2, help="中文标题行(默认第 2 行)")
ap.add_argument("--key-row", type=int, default=1,
help="英文字段名行(默认第 1 行);设 0 表示不打印该行")
ap.add_argument("--title", default="")
ap.add_argument("--out", default="tools/out/sheet.pdf")
ap.add_argument("--fontsize", type=float, default=9.0)
ap.add_argument("--landscape", action="store_true")
ap.add_argument("--keep-bad", action="store_true", help="不过滤 0/错误/空")
ap.add_argument("--print-to", default=None, help="打印机 IPv4/IPv6 地址,给了就打印")
ap.add_argument("--yes", action="store_true", help="确认真正打印")
ap.add_argument("--allow-empty", action="store_true", help="0 行时也允许打印空表")
ap.add_argument("--total", action="store_true", help="末尾加合计行(数字列求和)")
a = ap.parse_args()
path, n = build_pdf(a.file, a.sheet, a.col, a.header_row,
a.title or (a.sheet or ""), a.out,
drop_bad=not a.keep_bad, landscape=a.landscape, fontsize=a.fontsize,
key_row=a.key_row or None, with_total=a.total)
print(f"PDF: {path} 数据行={n} 大小={Path(path).stat().st_size/1024:.1f} KB")
if a.print_to:
if n == 0:
print("过滤后 0 行,已跳过打印(确实要打空表加 --allow-empty)")
if not a.allow_empty:
return 0
sys.path.insert(0, str(Path(__file__).parent))
from printer_client import PrinterClient, render_pages
pages = render_pages(Path(path), dpi=300)
c = PrinterClient(a.print_to)
if not a.yes:
print(f"[干跑] 将发送 {len(pages)} 页 -> {c.uri}")
return 0
for i, pg in enumerate(pages, 1):
r = c.print_job(pg, "image/jpeg", job_name=f"sheet-{i}",
media="iso_a4_210x297mm", color="color")
print(f" Print-Job 页{i} -> {r['status']}")
return 0
if __name__ == "__main__":
sys.exit(main())