ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

HoRain云--Python 自动化办公:Excel、Word、PDF、邮件全流程

HoRain云--Python 自动化办公:Excel、Word、PDF、邮件全流程 1. 场景介绍每月需要从 Excel 读取销售数据生成 Word 报告导出 PDF并邮件发送给领导。手工操作耗时且易错用 Python 可一键完成。2. 环境准备bash复制下载pip install openpyxl python-docx docx2pdf pandas pywin323. 读取 Excelpython复制下载import pandas as pd df pd.read_excel(sales.xlsx, sheet_nameSheet1) total df[金额].sum() top df.nlargest(5, 金额)4. 处理数据python复制下载summary df.groupby(地区)[金额].sum().reset_index() summary summary.sort_values(金额, ascendingFalse)5. 生成 Word 报告python复制下载from docx import Document from docx.shared import Inches doc Document() doc.add_heading(销售月报, level0) doc.add_paragraph(f总销售额{total:.2f} 元) doc.add_heading(地区汇总, level1) table doc.add_table(rows1, cols2) table.style Light Grid Accent 1 hdr table.rows[0].cells hdr[0].text 地区 hdr[1].text 金额 for _, row in summary.iterrows(): cells table.add_row().cells cells[0].text row[地区] cells[1].text f{row[金额]:.2f} doc.save(report.docx)6. Word 转 PDFWindows 下可用 docx2pdfpython复制下载from docx2pdf import convert convert(report.docx, report.pdf)Linux 可使用 LibreOfficebash复制下载libreoffice --headless --convert-to pdf report.docx7. 发送邮件python复制下载import smtplib from email.message import EmailMessage msg EmailMessage() msg[Subject] 销售月报 msg[From] senderexample.com msg[To] bossexample.com msg.set_content(附件为本月销售报告请查收。) with open(report.pdf, rb) as f: msg.add_attachment(f.read(), maintypeapplication, subtypepdf, filenamereport.pdf) with smtplib.SMTP_SSL(smtp.example.com, 465) as smtp: smtp.login(senderexample.com, password) smtp.send_message(msg)8. 定时执行使用 schedulepython复制下载import schedule import time def job(): # 执行上述流程 pass schedule.every().monday.at(09:00).do(job) while True: schedule.run_pending() time.sleep(60)或使用 Windows 任务计划、Linux cron。9. 常见坑Excel 文件被占用导致读取失败。邮件授权码不是登录密码。PDF 转换依赖 Office 或 LibreOffice。附件过大被拒收。10. 总结Python 自动化办公可以大幅减少重复劳动。掌握 pandas、python-docx、smtplib 后可以扩展到报表、合同、发票等场景。
返回列表