Python自动化脚本如何实现办公提效

wen 实用脚本 1

本文目录导读:

Python自动化脚本如何实现办公提效

  1. Python自动化办公的核心优势
  2. 常用自动化库
  3. 实战案例
  4. 高级应用场景
  5. 最佳实践建议

我来详细介绍Python自动化办公提效的实践方法和具体案例。

Python自动化办公的核心优势

  • 批量处理:一次性处理大量重复性工作
  • 准确性高:避免人工操作导致的错误
  • 24小时运行:可以定时执行,不占用工作时间
  • 跨平台兼容:Windows/Mac/Linux都能运行

常用自动化库

# 文档处理
import openpyxl  # Excel操作
import python-docx  # Word操作  
import PyPDF2  # PDF处理
# 文件操作
import os
import shutil
import glob
# 邮件自动化
import smtplib
import yagmail
# 定时任务
import schedule
import time

实战案例

Excel批量处理

import openpyxl
from openpyxl.styles import PatternFill, Font
import glob
def batch_process_excel():
    """批量处理Excel文件"""
    # 查找所有Excel文件
    excel_files = glob.glob("data/*.xlsx")
    for file in excel_files:
        wb = openpyxl.load_workbook(file)
        ws = wb.active
        # 添加样式
        header_fill = PatternFill(start_color="FF0000", end_color="FF0000", fill_type="solid")
        header_font = Font(bold=True, color="FFFFFF")
        # 格式化表头
        for cell in ws[1]:
            cell.fill = header_fill
            cell.font = header_font
        # 保存
        wb.save(f"processed_{file}")
# 自动合并多个Excel
def merge_excel_files():
    """合并多个Excel文件"""
    wb_merged = openpyxl.Workbook()
    ws_merged = wb_merged.active
    for file in glob.glob("data/*.xlsx"):
        wb = openpyxl.load_workbook(file)
        ws = wb.active
        for row in ws.iter_rows(values_only=True):
            ws_merged.append(row)
    wb_merged.save("merged_result.xlsx")

邮件自动发送

import yagmail
import pandas as pd
def send_bulk_emails():
    """批量发送个性化邮件"""
    # 读取联系人信息
    df = pd.read_excel("contacts.xlsx")
    # 配置邮箱
    yag = yagmail.SMTP(
        user="your_email@gmail.com",
        password="your_password",
        host="smtp.gmail.com"
    )
    # 批量发送
    for _, row in df.iterrows():
        content = f"""
        尊敬的{row['name']}:
        您好!感谢您对本次活动的关注。
        您的专属优惠码是:{row['code']}
        有效期为:2024年底
        祝好!
        """
        yag.send(
            to=row['email'],
            subject="【专属优惠通知】",
            contents=content
        )
        print(f"已发送给 {row['name']}")

文件智能整理

import os
import shutil
from pathlib import Path
def organize_files():
    """智能整理文件"""
    # 文件分类规则
    file_categories = {
        '文档': ['.docx', '.pdf', '.txt', '.xlsx'],
        '图片': ['.jpg', '.png', '.gif', '.bmp'],
        '视频': ['.mp4', '.avi', '.mkv'],
        '压缩包': ['.zip', '.rar', '.7z'],
    }
    # 创建分类文件夹
    for category in file_categories:
        os.makedirs(category, exist_ok=True)
    # 移动文件
    for file in Path('.').glob('*'):
        if file.is_file():
            ext = file.suffix.lower()
            for category, extensions in file_categories.items():
                if ext in extensions:
                    shutil.move(str(file), f"{category}/{file.name}")
                    print(f"移动 {file.name} -> {category}/")
                    break
# 定时清理临时文件
def clean_temp_files():
    """清理临时文件"""
    temp_dirs = ['temp', 'tmp', '__pycache__', '.ipynb_checkpoints']
    for dir_name in temp_dirs:
        if os.path.exists(dir_name):
            shutil.rmtree(dir_name)
            print(f"已删除 {dir_name}")
    # 删除大于30天的日志文件
    for log_file in Path('logs').glob('*.log'):
        if (time.time() - os.path.getmtime(log_file)) > 30 * 24 * 3600:
            os.remove(log_file)
            print(f"已删除旧日志{log_file}")

定时任务调度

import schedule
import time
from datetime import datetime
def daily_report():
    """生成日报表"""
    print(f"生成日报表 - {datetime.now()}")
    # 具体的报表生成逻辑
    generate_report()
def weekly_backup():
    """每周备份"""
    print(f"执行周备份 - {datetime.now()}")
    backup_files()
def monitor_system():
    """系统监控"""
    # 检查磁盘空间
    import psutil
    disk_usage = psutil.disk_usage('/')
    if disk_usage.percent > 90:
        send_alert_email("磁盘空间不足!")
# 设置定时任务
def setup_schedule():
    # 每天早上9点生成日报
    schedule.every().day.at("09:00").do(daily_report)
    # 每周一凌晨3点备份
    schedule.every().monday.at("03:00").do(weekly_backup)
    # 每30分钟检查系统状态
    schedule.every(30).minutes.do(monitor_system)
    # 每小时同步数据
    schedule.every().hour.do(sync_data)
    while True:
        schedule.run_pending()
        time.sleep(1)
if __name__ == "__main__":
    setup_schedule()

批量重命名工具

import os
import re
from pathlib import Path
def batch_rename():
    """批量重命名文件"""
    pattern = input("请输入命名模式 (使用{n}表示序号): ")
    start_num = int(input("起始编号: "))
    file_type = input("文件类型 (如: .jpg, .pdf): ")
    files = sorted(Path().glob(f"*{file_type}"))
    for i, file in enumerate(files, start_num):
        new_name = pattern.format(n=i) + file_type
        file.rename(new_name)
        print(f"{file.name} -> {new_name}")
def smart_rename():
    """智能重命名(去除特殊字符、统一格式)"""
    for file in Path().glob('*'):
        if file.is_file():
            # 移除特殊字符
            new_name = re.sub(r'[^\w\s.-]', '', file.stem)
            new_name = new_name.replace(' ', '_')
            new_name = new_name.lower()
            new_full_name = new_name + file.suffix
            if new_full_name != file.name:
                file.rename(new_full_name)
                print(f"重命名: {file.name} -> {new_full_name}")

高级应用场景

网页数据抓取

import requests
from bs4 import BeautifulSoup
import pandas as pd
def scrape_web_data():
    """自动抓取网页数据"""
    url = "https://example.com/data"
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    data = []
    for row in soup.select('table tr'):
        cols = row.find_all('td')
        if cols:
            data.append([col.text.strip() for col in cols])
    df = pd.DataFrame(data)
    df.to_excel("web_data.xlsx", index=False)

系统监控与告警

import psutil
import socket
import yagmail
def system_monitor():
    """系统监控自动化"""
    alerts = []
    # CPU使用率
    cpu_percent = psutil.cpu_percent(interval=1)
    if cpu_percent > 80:
        alerts.append(f"CPU使用率过高: {cpu_percent}%")
    # 内存使用
    memory = psutil.virtual_memory()
    if memory.percent > 90:
        alerts.append(f"内存使用率过高: {memory.percent}%")
    # 磁盘使用
    disk = psutil.disk_usage('/')
    if disk.percent > 85:
        alerts.append(f"磁盘使用率过高: {disk.percent}%")
    # 发送告警
    if alerts:
        send_alert_email("\n".join(alerts))

最佳实践建议

开发流程

  1. 分析需求:确定哪些工作重复性高、规则明确
  2. 小步迭代:先实现核心功能,逐步完善
  3. 异常处理:添加try-except处理各种异常情况
  4. 日志记录:记录运行日志便于排查问题
  5. 版本控制:使用Git管理代码版本

注意事项

  • 测试验证:先在测试环境验证后再用于生产
  • 数据备份:处理重要数据前先备份
  • 权限控制:确保脚本有合适的执行权限
  • 安全考虑:避免硬编码密码等敏感信息

效率提升技巧

# 使用配置文件和环境变量
import os
from dotenv import load_dotenv
load_dotenv()
EMAIL_PASSWORD = os.getenv('EMAIL_PASSWORD')
# 并行处理提高效率
from concurrent.futures import ThreadPoolExecutor
def process_file(file):
    # 处理单个文件
    pass
with ThreadPoolExecutor(max_workers=5) as executor:
    executor.map(process_file, file_list)

通过这些实战案例,你可以快速开始Python办公自动化,建议从最简单的文件整理开始,逐步过渡到更复杂的场景。自动化成功的关键不是技术有多复杂,而是能否真正解决实际问题

抱歉,评论功能暂时关闭!