# 办公文件处理 Skill 处理用户发来的 Word (.docx)、Excel (.xlsx)、PowerPoint (.pptx)、PDF (.pdf) 等办公文件。 ## 工作流程 ``` 收到用户文件请求 ↓ 从 files/ 目录找到文件(或先用 qq_get_file.py 下载) ↓ 复制到 self-workplace/ 下处理(避免污染原文件) ↓ 用 Python 脚本处理并输出结果 ↓ 将处理结果通过 qq_send_msg.py 或 qq_send_file.py 发送给用户 ↓ 删除 self-workplace/ 下的临时副本 ``` ## 环境 虚拟环境位置:`YOUR_WORKSPACE_PATH/self-workplace/.venv` 用 `.venv/bin/python3` 调用,或用 `source .venv/bin/activate` 激活后直接 `python3`。 已安装的包: | 包 | 用途 | 支持格式 | |---|---|---| | python-docx | 读写 Word 文档 | .docx | | python-pptx | 读写 PPT 演示文稿 | .pptx | | openpyxl | 读写 Excel 工作簿 | .xlsx | | PyMuPDF (fitz) | PDF 通用解析(文字/图片/元数据) | .pdf | | pdfplumber | PDF 精确提取(表格友好) | .pdf | | Pillow | 图片处理 | .jpg/.png | ## 使用方法 ### 1. Word (.docx) — python-docx ```python from docx import Document doc = Document("self-workplace/文件名.docx") # 读取所有段落 for para in doc.paragraphs: print(f"[{para.style.name}] {para.text}") # 读取表格 for table in doc.tables: for row in table.rows: print(" | ".join(cell.text for cell in row.cells)) # 修改后保存 # doc.save("self-workplace/输出.docx") ``` ### 2. PowerPoint (.pptx) — python-pptx ```python from pptx import Presentation prs = Presentation("self-workplace/文件名.pptx") for slide in prs.slides: print(f"--- 幻灯片 {slide.slide_id} ---") for shape in slide.shapes: if shape.has_text_frame: text = shape.text_frame.text.strip() if text: print(text) if shape.has_table: table = shape.table for row in table.rows: print(" | ".join(cell.text for cell in row.cells)) ``` ### 3. Excel (.xlsx) — openpyxl ```python from openpyxl import load_workbook wb = load_workbook("self-workplace/文件名.xlsx", data_only=True) # 工作表列表 print("工作表:", wb.sheetnames) # 读取第一个工作表 ws = wb.active for row in ws.iter_rows(values_only=True): print(" | ".join(str(cell) if cell is not None else "" for cell in row)) ``` ### 4. PDF — PyMuPDF(通用提取) ```python import fitz doc = fitz.open("self-workplace/文件名.pdf") print(f"共 {len(doc)} 页") for page_num in range(len(doc)): page = doc[page_num] text = page.get_text() print(f"--- 第 {page_num+1} 页 ---") print(text) ``` ### 5. PDF 表格 — pdfplumber(表格提取) ```python import pdfplumber with pdfplumber.open("self-workplace/文件名.pdf") as pdf: for i, page in enumerate(pdf.pages): tables = page.extract_tables() for t_idx, table in enumerate(tables): print(f"--- 第 {i+1} 页 表格 {t_idx+1} ---") for row in table: print(" | ".join(str(c) if c else "" for c in row)) ``` ## 注意事项 1. **复制到 self-workplace 处理**:先 cp 过去再处理,原始文件不动,处理完删临时副本 2. **处理完发送结果**:用 `qq_send_msg.py` 发文字摘要,或 `qq_send_file.py` 发生成的文档 3. **必须清理**:处理完成后删除 `self-workplace/` 下的副本,防止堆积 4. **编码问题**:Python 默认 utf-8,一般没问题。中文 .docx 如果有乱码可尝试 `encoding="utf-8"`