Python 自动化办公的 10 大脚本

在现代办公环境中,自动化脚本可以显著提升工作效率。以下是 10 个常见的办公问题及其对应的 Python 自动化解决方案。

1. 批量重命名文件

如果你需要对一堆文件进行重命名,比如给文件添加前缀或后缀,可以使用以下脚本:

python 复制代码
import os

def batch_rename_files(directory, prefix):
    """批量重命名指定目录下的所有文件,添加前缀"""
    for filename in os.listdir(directory):
        new_name = f"{prefix}_{filename}"
        os.rename(os.path.join(directory, filename), os.path.join(directory, new_name))
    print("文件重命名完成")

batch_rename_files('path/to/your/directory', 'new_prefix')

2. Excel 数据合并

合并多个 Excel 文件中的数据到一个单一文件中:

python 复制代码
import pandas as pd

def merge_excels(file_list, output_file):
    df_list = []
    for file in file_list:
        df = pd.read_excel(file)
        df_list.append(df)
    merged_df = pd.concat(df_list, ignore_index=True)
    merged_df.to_excel(output_file, index=False)

file_list = ['file1.xlsx', 'file2.xlsx', 'file3.xlsx']
merge_excels(file_list, 'merged_output.xlsx')

3. 填充空缺值

批量填充 Excel 文件中的空缺值:

python 复制代码
import pandas as pd

def fill_na_excel(input_file, output_file, fill_value):
    df = pd.read_excel(input_file)
    df.fillna(fill_value, inplace=True)
    df.to_excel(output_file, index=False)

fill_na_excel('input.xlsx', 'filled_output.xlsx', fill_value=0)

4. Excel 表匹配

将两个表中的数据根据共同列匹配合并:

python 复制代码
import pandas as pd

def merge_on_column(file_a, file_b, column_name, output_file):
    df_a = pd.read_excel(file_a)
    df_b = pd.read_excel(file_b)
    merged_df = pd.merge(df_a, df_b, on=column_name, how='left')
    merged_df.to_excel(output_file, index=False)

merge_on_column('a.xlsx', 'b.xlsx', 'name', 'matched_output.xlsx')

5. Excel 数据汇总

根据部门汇总工资数据:

python 复制代码
import pandas as pd

def summarize_salary_by_department(input_file, output_file):
    df = pd.read_excel(input_file)
    summary = df.groupby('部门')['工资'].sum().reset_index()
    summary.to_excel(output_file, index=False)

summarize_salary_by_department('工资条.xlsx', '部门工资汇总.xlsx')

6. 考勤数据分析

统计每个用户迟到、旷到次数,并判断是否全勤:

python 复制代码
import pandas as pd

def analyze_attendance(input_file, output_file):
    df = pd.read_excel(input_file)
    df['打卡时间'] = pd.to_datetime(df['打卡时间'])
    df['迟到'] = df['打卡时间'] > pd.to_datetime(df['上班时间']) + pd.Timedelta(minutes=30)
    df['旷到'] = df['打卡时间'] > pd.to_datetime(df['上班时间']) + pd.Timedelta(minutes=120)

    result = df.groupby('用户').agg(
        迟到次数=('迟到', 'sum'),
        旷到次数=('旷到', 'sum')
    ).reset_index()

    result['全勤'] = (result['迟到次数'] == 0) & (result['旷到次数'] == 0)

    result.to_excel(output_file, index=False)

analyze_attendance('考勤数据.xlsx', '考勤分析.xlsx')

7. 批量生成邀请函

批量生成包含不同姓名的邀请函:

python 复制代码
from docx import Document

def create_invitations(names, template_file, output_folder):
    for name in names:
        doc = Document(template_file)
        for paragraph in doc.paragraphs:
            if '{{name}}' in paragraph.text:
                paragraph.text = paragraph.text.replace('{{name}}', name)
        doc.save(os.path.join(output_folder, f'邀请函_{name}.docx'))

names = ['Alice', 'Bob', 'Charlie']
create_invitations(names, 'template.docx', 'invitations')

8. 网页表格数据整理到 Excel

解析 HTML 源文件中的表格数据并存储到 Excel 文件中:

python 复制代码
import pandas as pd
from bs4 import BeautifulSoup

def parse_html_to_excel(html_file, output_file):
    with open(html_file, 'r', encoding='utf-8') as file:
        soup = BeautifulSoup(file, 'html.parser')

    tables = soup.find_all('table')
    df_list = []

    for table in tables:
        df = pd.read_html(str(table))[0]
        df_list.append(df)

    combined_df = pd.concat(df_list, ignore_index=True)
    combined_df.to_excel(output_file, index=False)

parse_html_to_excel('table.html', 'parsed_output.xlsx')

9. 自动发送邮件

结合之前的数据处理结果自动发送邮件:

python 复制代码
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def send_email(to_email, subject, body, attachment_path):
    from_email = "your_email@example.com"
    password = "your_password"

    msg = MIMEMultipart()
    msg['From'] = from_email
    msg['To'] = to_email
    msg['Subject'] = subject

    msg.attach(MIMEText(body, 'plain'))

    with open(attachment_path, 'rb') as attachment:
        part = MIMEText(attachment.read(), 'base64', 'utf-8')
        part['Content-Disposition'] = f'attachment; filename={os.path.basename(attachment_path)}'
        msg.attach(part)

    server = smtplib.SMTP('smtp.example.com', 587)
    server.starttls()
    server.login(from_email, password)
    server.sendmail(from_email, to_email, msg.as_string())
    server.quit()

send_email('recipient@example.com', 'Subject', 'Email body', 'attachment.xlsx')

10. 数据库导入导出

从数据库导出数据并进行处理后重新导入:

python 复制代码
import pandas as pd
from sqlalchemy import create_engine

def export_import_database(db_url, query, table_name):
    engine = create_engine(db_url)
    df = pd.read_sql(query, engine)

    # 进行数据处理,例如删除重复值
    df.drop_duplicates(inplace=True)

    df.to_sql(table_name, engine, if_exists='replace', index=False)

db_url = 'mysql+pymysql://user:password@host/dbname'
query = 'SELECT * FROM source_table'
export_import_database(db_url, query, 'destination_table')

这些 Python 脚本涵盖了办公中常见的数据处理、分析和自动化任务,能够显著提升工作效率和准确性。希望这些脚本能帮助你更好地实现自动化办公。

相关推荐
人间乄惊鸿客3 小时前
python - 第二天
python
江上月5133 小时前
django与vue3的对接流程详解(上)
后端·python·django
老歌老听老掉牙3 小时前
基于 PyQt5 实现刀具类型选择界面的设计与交互逻辑
python·qt·交互
可触的未来,发芽的智生3 小时前
触摸未来2025.10.09:记忆的突围,从64个神经元到人工海马体神经网络
人工智能·python·神经网络·机器学习·架构
川石课堂软件测试4 小时前
什么是BUG,你对BUG的了解有多少?
android·linux·服务器·python·功能测试·bug·安全性测试
风之所往_4 小时前
使用 openpyxl 生成 excel 折线图
python·excel·openpyxl
努力也学不会java4 小时前
【Java并发】揭秘Lock体系 -- 深入理解ReentrantReadWriteLock
java·开发语言·python·机器学习
我的xiaodoujiao7 小时前
从 0 到 1 搭建 Python 语言 Web UI自动化测试学习系列 15--二次开发--封装公共方法 3
python·学习·测试工具
AI视觉网奇7 小时前
pyqt 触摸屏监听
开发语言·python·pyqt