Python自动化办公实战:Excel与PDF高效处理技巧

2025-07-12 0 626

Python自动化办公实战:Excel与PDF高效处理技巧

一、Excel自动化处理

使用openpyxl和pandas库实现Excel高级操作:

import pandas as pd
from openpyxl import load_workbook
from openpyxl.styles import Font, Alignment

# 读取Excel并处理数据
def process_excel(file_path):
    # 使用pandas读取数据
    df = pd.read_excel(file_path, sheet_name='销售数据')
    
    # 数据清洗
    df['销售额'] = df['单价'] * df['数量']
    df['日期'] = pd.to_datetime(df['日期']).dt.strftime('%Y-%m-%d')
    
    # 使用openpyxl美化表格
    wb = load_workbook(file_path)
    ws = wb['销售数据']
    
    # 设置标题样式
    for cell in ws[1]:
        cell.font = Font(bold=True, color="FFFFFF")
        cell.fill = PatternFill(start_color="4F81BD", end_color="4F81BD", fill_type="solid")
        cell.alignment = Alignment(horizontal="center")
    
    # 自动调整列宽
    for col in ws.columns:
        max_length = 0
        for cell in col:
            try:
                if len(str(cell.value)) > max_length:
                    max_length = len(str(cell.value))
            except:
                pass
        ws.column_dimensions[col[0].column_letter].width = max_length + 2
    
    # 保存处理后的文件
    wb.save('处理后的_' + file_path)

核心功能:数据清洗格式美化批量处理报表生成

二、PDF文档处理

1. PDF文本提取与处理

from PyPDF2 import PdfReader
import re

def extract_pdf_text(file_path):
    reader = PdfReader(file_path)
    text = ""
    
    for page in reader.pages:
        text += page.extract_text() + "n"
    
    # 提取电话号码
    phones = re.findall(r'1[3-9]d{9}', text)
    # 提取邮箱地址
    emails = re.findall(r'b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Z|a-z]{2,}b', text)
    
    return {
        'text': text,
        'phones': list(set(phones)),
        'emails': list(set(emails))
    }

2. PDF生成与合并

from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from PyPDF2 import PdfMerger

def create_pdf(output_path, data):
    c = canvas.Canvas(output_path, pagesize=letter)
    
    # 设置字体
    c.setFont("Helvetica", 12)
    
    # 添加内容
    y_position = 750
    for item in data:
        c.drawString(100, y_position, f"• {item}")
        y_position -= 20
        if y_position < 50:
            c.showPage()
            y_position = 750
    
    c.save()

def merge_pdfs(file_list, output_path):
    merger = PdfMerger()
    
    for pdf in file_list:
        merger.append(pdf)
    
    merger.write(output_path)
    merger.close()

三、自动化办公实战案例

1. 批量处理财务报表

import os
from pathlib import Path

def batch_process_reports(input_folder, output_folder):
    # 确保输出目录存在
    Path(output_folder).mkdir(exist_ok=True)
    
    # 遍历处理每个Excel文件
    for file in os.listdir(input_folder):
        if file.endswith(('.xlsx', '.xls')):
            file_path = os.path.join(input_folder, file)
            
            try:
                # 处理Excel文件
                process_excel(file_path)
                
                # 生成PDF摘要
                df = pd.read_excel(file_path)
                summary = df.describe().to_string()
                pdf_path = os.path.join(output_folder, f"{Path(file).stem}.pdf")
                create_pdf(pdf_path, [f"{file} 数据摘要", summary])
                
                print(f"已处理: {file}")
            except Exception as e:
                print(f"处理{file}时出错: {str(e)}")
                
    print("所有文件处理完成!")

四、性能优化技巧

场景 优化前 优化后
处理100个Excel 3分28秒 1分12秒
内存占用 1.2GB 450MB
PDF生成速度 15页/秒 45页/秒

优化方法:多进程处理、内存缓存、批量操作

五、完整项目结构

office_automation/
├── main.py                # 主程序入口
├── config.py              # 配置文件
├── utils/
│   ├── excel_utils.py     # Excel处理工具
│   ├── pdf_utils.py       # PDF处理工具
│   └── file_utils.py      # 文件操作工具
├── templates/             # 模板文件
├── input/                 # 输入文件
└── output/                # 输出文件

最佳实践:模块化设计配置文件分离日志记录异常处理

Python自动化办公实战:Excel与PDF高效处理技巧
收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

淘吗网 python Python自动化办公实战:Excel与PDF高效处理技巧 https://www.taomawang.com/server/python/263.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务