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

相关推荐
iCxhust6 小时前
windows环境下在Bochs中运行Linux0.12系统
linux·运维·服务器·windows·minix
梦想画家9 小时前
基于PyTorch的时间序列异常检测管道构建指南
人工智能·pytorch·python
PythonFun10 小时前
OCR图片识别翻译工具功能及源码
python·ocr·机器翻译
虫师c11 小时前
Python浪漫弹窗程序:Tkinter实现动态祝福窗口教程
python·tkinter·动画效果·gui编程·弹窗效果
wanhengidc12 小时前
云手机搬砖 尤弥尔传奇自动化操作
运维·服务器·arm开发·安全·智能手机·自动化
灯火不休时12 小时前
95%准确率!CNN交通标志识别系统开源
人工智能·python·深度学习·神经网络·cnn·tensorflow
deephub12 小时前
FastMCP 入门:用 Python 快速搭建 MCP 服务器接入 LLM
服务器·人工智能·python·大语言模型·mcp
南宫乘风12 小时前
基于 Flask + APScheduler + MySQL 的自动报表系统设计
python·mysql·flask
番石榴AI12 小时前
基于机器学习优化的主图选择方法(酒店,景点,餐厅等APP上的主图展示推荐)
图像处理·人工智能·python·机器学习
qq74223498413 小时前
Python操作数据库之pyodbc
开发语言·数据库·python