Python 10个自动化办公脚本

科技   2024-08-08 18:43   浙江  

自动化,很简单10个Python自动化办公脚本

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

插播:现在下载我们自己开发的 想读APP,阅读、学习文章更简单,点击查看想读安装使用说明。

如果你有其他自动化需求,都可以加文末我的微信,免费给你设计自动化方案,让你的工作更简单!

1. Excel数据合并

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

import pandas as pd
import os

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')

2. 填充空缺值

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

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)

3. Excel表匹配

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

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')

4. Excel数据汇总

根据部门汇总工资数据。

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')

5. 考勤数据分析

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

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')

6. 批量生成邀请函

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

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')

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

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

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')

8. 自动发送邮件

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

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')

9. 批量数据处理

批量处理多个文件中的数据并输出结果。

import pandas as pd

def batch_process(files, output_folder):
    for file in files:
        df = pd.read_excel(file)
        # 进行数据处理,例如填充空缺值
        df.fillna(0, inplace=True)
        output_file = os.path.join(output_folder, os.path.basename(file))
        df.to_excel(output_file, index=False)

files = ['file1.xlsx''file2.xlsx''file3.xlsx']
batch_process(files, 'processed_files')

10. 数据库导入导出

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

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脚本涵盖了办公中常见的数据处理、分析和自动化任务,能够显著提升工作效率和准确性。

如果你有更具体需求,欢迎在评论区评论,下期,我就帮你实现办公自动化,让工作更简单。

加入我们


扫码加我微信,回复:AI阅读
一起迎接AI时代

简说Python
号主老表,自学,分享Python,SQL零基础入门、数据分析、数据挖掘、机器学习优质文章以及学习经验。
 最新文章