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

相关推荐
用户835629078051几秒前
使用 Python 操作 Word 内容控件
后端·python
qq_369224331 小时前
Windows全系通用!ntdll.dll文件丢失、报错、闪退问题的完整排查与修复教程
windows·dll·dll修复·dll丢失·dll错误
码云骑士2 小时前
32-慢查询排查全流程(下)-索引优化实战与最左前缀原则
python
shushangyun_2 小时前
2026年快消品B2B系统推荐:支持终端门店订货、促销政策自动化的工具?
java·运维·网络·数据库·人工智能·spring·自动化
闵孚龙2 小时前
《PyTorch 深度修炼》Dataset 和 DataLoader:数据如何喂给模型
人工智能·pytorch·python
goldenrolan2 小时前
A公司物料替代测试系统 v1.7:从需求到 exe/apk 的 AI 辅助全链路实践
android·自动化测试·软件测试·python·ai
菜板春2 小时前
jupyter入门-手册-特征探索
python·jupyter
Metaphor6923 小时前
使用 Python 将 PDF 转换为 HTML
python·pdf·html
施努卡机器视觉3 小时前
SNK施努卡侧滑门锁上滑轮总成自动化装配线,从零件到组件,全流程精密制造方案
运维·自动化·制造