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

相关推荐
涛声依旧-底层原理研究所31 分钟前
残差连接与层归一化通俗易懂的详解
人工智能·python·神经网络·transformer
csdn_aspnet37 分钟前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展
fantasy_arch1 小时前
pytorch人脸匹配模型
人工智能·pytorch·python
熊猫_豆豆1 小时前
广义相对论水星近日点进动完整详细数学推导
python·天体·广义相对论
裴东青1 小时前
10-实战:RuoYi-Cloud的自动化发布
运维·ci/cd·自动化
web3.08889991 小时前
1688 图搜接口(item_search_img / 拍立淘) 接入方法
开发语言·python
AI算法沐枫2 小时前
深度学习python代码处理科研测序数据
数据结构·人工智能·python·深度学习·决策树·机器学习·线性回归
迁移科技2 小时前
告别人工分拣!迁移科技 AI+3D 视觉让机器人 “看懂” 无序抓取
人工智能·科技·3d·机器人·自动化·视觉检测
xxx1x1x2 小时前
极客向:DLL/运行库故障的底层逻辑与自动化修复方案
运维·自动化·dll文件·dll·dll修复·dll缺失·dll一键修复
X1A0RAN3 小时前
解决Pycharm中部分文件或文件夹被隐藏不展示问题
ide·python·pycharm