用途:使用 Python 和 openpyxl 处理 Excel .xlsx 工作簿,构建带样式、多工作表、公式与图表的文件,检查或转储已有文件,编辑单元格与结构,并与 CSV 互转。所有辅助脚本均为 argparse CLI,输出 JSON,使用显式 UTF-8 I/O。
主要能力:创建多表报表,支持数字格式、样式、合并单元格、冻结窗格、自动筛选、条件格式、图表、数据验证下拉、原生 Excel 表格、定义名称、超链接、单元格批注、工作表保护;读取工作簿的清单、数据、公式与缓存值、批注、定义名称、表格;编辑单元格、追加行、插入删除行列(通过 xlsx_restructure.py 实现引用感知)、复制重命名工作表;用 LibreOffice 无头重算公式;CSV 互转支持类型推断与非 UTF-8 编码。不支持旧版 .xls 二进制格式,需先用 LibreOffice 转换:soffice --headless --convert-to xlsx old.xls。
先决条件:Python 3.10+ 及 openpyxl(pip install openpyxl)。可选 LibreOffice(soffice)用于无头重算或格式转换。
运行方式:在本技能的 scripts/ 目录下用终端工具运行,各脚本均支持 --help。 python scripts/xlsx_create.py spec.json report.xlsx python scripts/xlsx_read.py report.xlsx --sheets python scripts/xlsx_read.py report.xlsx --json --sheet Data python scripts/xlsx_read.py report.xlsx --formulas python scripts/xlsx_edit.py report.xlsx --sheet Data --set B2=42 --recalc python scripts/xlsx_restructure.py report.xlsx --sheet Data --insert-rows 3:2 python scripts/xlsx_recalc.py report.xlsx python scripts/csv_to_xlsx.py data.csv out.xlsx --encoding utf-8 python scripts/xlsx_to_csv.py report.xlsx out.csv --sheet Data
注意事项:openpyxl 不计算公式,公式结果仅在文件由 Excel/LibreOffice 保存过且用 data_only=True 加载时可得,否则为 None。写公式时应在 spec 中加 full_calc_on_load 或编辑器加 --recalc,让应用打开时重算。xlsx_edit.py 的插入删除不移动引用,需用 xlsx_restructure.py。工作表保护不是安全措施,不加密内容。加载会剥离图表和图片,编辑带图表的工作簿并保存会丢失图表。CSV 需显式指定编码,欧洲 CSV 常用分号分隔和小数逗号。日期以 datetime 返回、转储为 ISO 字符串。工作表名上限 31 字符,禁用 [ ] : * ? / \。
验证:创建后用 --sheets 确认名称、维度、合并范围与图表数;用 --json 对比数据;编辑后重新转储受影响区域,确认 --formulas 列出公式且已应用 --recalc;restructure 后读取其 JSON 报告,再运行 --formulas 和 --sheets 确认引用与区域。可用 soffice --headless --convert-to pdf out.xlsx 做完整视觉检查。