python 提供了丰富的库来处理 office 文档(word、excel、powerpoint)、pdf 以及电子邮件等办公自动化任务。
excel 处理
1. 主流 excel 库
openpyxl (推荐)
# 安装: pip install openpyxl
from openpyxl import workbook
wb = workbook()
ws = wb.active
ws['a1'] = 42
ws.append([1, 2, 3])
wb.save("example.xlsx")特点:
- 读写.xlsx格式
- 支持公式、图表、样式
- 不依赖excel软件
- 内存友好
xlwings
# 安装: pip install xlwings
import xlwings as xw
wb = xw.book() # 新建excel
sheet = wb.sheets['sheet1']
sheet.range('a1').value = 'hello'
wb.save('test.xlsx')
wb.close()特点:
- 可操作已打开的excel
- 支持vba调用
- 需要安装excel软件
pandas (数据处理首选)
# 安装: pip install pandas openpyxl
import pandas as pd
# 读取
df = pd.read_excel("input.xlsx", sheet_name="sheet1")
# 处理数据
df['new_col'] = df['col1'] * 2
# 写入
df.to_excel("output.xlsx", index=false)特点:
- 强大的数据处理能力
- 依赖openpyxl/xlrd作为后端
- 适合大数据量操作
2. 其他excel库
| 库名 | 特点 | 适用场景 |
|---|---|---|
| xlrd/xlwt | 只支持.xls格式 | 旧版excel文件处理 |
| pyxlsb | 读取.xlsb二进制文件 | 大数据量excel文件 |
| xlsxwriter | 仅写入,功能强大 | 生成复杂报表 |
word 文档处理
1. python-docx (推荐)
# 安装: pip install python-docx
from docx import document
doc = document()
doc.add_heading('python生成的文档', 0)
doc.add_paragraph('这是一个段落')
doc.add_table(rows=2, cols=2)
doc.save('demo.docx')特点:
- 读写.docx文件
- 支持段落、表格、图片
- 样式设置丰富
2. docx2pdf (转换工具)
# 安装: pip install docx2pdf
from docx2pdf import convert
convert("input.docx", "output.pdf")3. 其他word处理库
pywin32: 通过com接口控制word软件
docx-mailmerge: 邮件合并功能
python-docx-template: 模板化生成word
powerpoint 处理
python-pptx
# 安装: pip install python-pptx
from pptx import presentation
prs = presentation()
slide = prs.slides.add_slide(prs.slide_layouts[1])
slide.shapes.title.text = "python生成的ppt"
slide.placeholders[1].text = "内容区域"
prs.save('test.pptx')特点:
- 创建和更新.pptx文件
- 支持幻灯片、形状、图表
- 可添加图片和动画效果
pdf 处理
1. pypdf2 (基础操作)
# 安装: pip install pypdf2
from pypdf2 import pdffilereader, pdffilewriter
reader = pdffilereader("input.pdf")
writer = pdffilewriter()
writer.addpage(reader.getpage(0))
with open("output.pdf", "wb") as f:
writer.write(f)2. pdfkit (html转pdf)
# 安装: pip install pdfkit
# 需要额外安装wkhtmltopdf
import pdfkit
pdfkit.from_file('input.html', 'output.pdf')3. reportlab (生成pdf)
# 安装: pip install reportlab
from reportlab.pdfgen import canvas
c = canvas.canvas("hello.pdf")
c.drawstring(100, 750, "welcome to reportlab!")
c.save()4. 其他pdf库
| 库名 | 特点 |
|---|---|
| pdfminer.six | 提取pdf文本和元数据 |
| pdf2docx | pdf转word |
| fpdf2 | 轻量级pdf生成库 |
电子邮件处理
1. 发送邮件 (smtplib + email)
import smtplib
from email.mime.multipart import mimemultipart
from email.mime.text import mimetext
msg = mimemultipart()
msg['from'] = 'me@example.com'
msg['to'] = 'you@example.com'
msg['subject'] = 'python邮件测试'
msg.attach(mimetext('邮件正文内容', 'plain'))
server = smtplib.smtp('smtp.example.com', 587)
server.starttls()
server.login('user', 'password')
server.send_message(msg)
server.quit()2. 读取邮件 (imaplib)
import imaplib
import email
mail = imaplib.imap4_ssl('imap.example.com')
mail.login('user@example.com', 'password')
mail.select('inbox')
typ, data = mail.search(none, 'all')
for num in data[0].split():
typ, msg_data = mail.fetch(num, '(rfc822)')
msg = email.message_from_bytes(msg_data[0][1])
print(msg['subject'])办公自动化综合工具
1. pywin32 (windows office自动化)
# 安装: pip install pywin32
import win32com.client
excel = win32com.client.dispatch("excel.application")
excel.visible = true
wb = excel.workbooks.add()
ws = wb.worksheets(1)
ws.cells(1,1).value = "hello excel"
wb.saveas("test.xlsx")
excel.quit()特点:
- 控制已安装的office软件
- 功能最全面
- 仅限windows系统
2. unoconv (文档格式转换)
# 需要安装libreoffice
import os
os.system('unoconv -f pdf test.docx') # word转pdf实践建议
格式选择:
- 数据处理优先使用excel+pandas
- 文档生成使用python-docx
- 复杂报表考虑jinja2模板+pdf
性能考虑:
# 大批量excel数据处理技巧
chunksize = 10**4
for chunk in pd.read_excel('large.xlsx', chunksize=chunksize):
process(chunk)安全注意事项:
- 处理用户上传的office文件时使用沙盒环境
- pdf处理注意恶意文件防护
- 邮件处理防范注入攻击
错误处理:
try:
doc = document("corrupted.docx")
except packagenotfounderror:
print("文件已损坏或不是有效的word文档")这些python库可以满足绝大多数办公自动化需求,从简单的数据导出到复杂的文档生成都能高效完成。根据具体需求选择合适的工具组合,可以显著提高办公效率。
以上就是python操作office(word/excel/powerpoint)文档的功能库使用详解的详细内容,更多关于python操作office文档的资料请关注代码网其它相关文章!
发表评论