办公及邮件


Python Word 操作
from docx import Document  # 导入docx
from docx.enum.style import WD_STYLE_TYPE  # 导入样式
from docx.enum.text import WD_ALIGN_PARAGRAPH  # 导入对齐
from docx.shared import Pt  # 导入字号
 
doc = Document()
 
for i in doc.styles:
    if i.type == WD_STYLE_TYPE.PARAGRAPH:  # 段落样式
        print(i.name)
    elif i.type == WD_STYLE_TYPE.CHARACTER:  # 字符样式
        print(i.name)
    elif i.type == WD_STYLE_TYPE.TABLE:  # 表格样式
        print(i.name)
 
"""普通添加标题和段落"""
 
doc.add_heading('这是文章的标题', level=0) 
doc.add_paragraph('这是段落样式一', 'Title')
doc.add_paragraph('这是段落样式二', 'Subtitle')
 
"""添加段落 设置右对齐 并追加内容 设置加粗和字号"""
 
p = doc.add_paragraph('这是段落样式三')
p.alignment = WD_ALIGN_PARAGRAPH.RIGHT
p_new = p.add_run('这是新增加的内容')
p_new.alignment = WD_ALIGN_PARAGRAPH.CENTER
p_new.font.bold = True
p_new.font.size = Pt(20)
 
"""添加图片和表格"""
doc.add_picture('12.jpg')
doc.save('dongli.docx')
table = doc.add_table(rows=5, cols=8)
table.cell(1, 1).text = '测试'
table.style = 'Light Grid Accent 3'
Python Excel操作
import openpyxl
 
xls = openpyxl.load_workbook('dongli.xlsx')
# print(xls.get_active_sheet()) 获取当前激活的工作表
 
# 获取单元格内容
sh1 = xls.active
cell1 = sh1['A1']
cell1.value
 
# 获取单元格的位置
cell1.coordinate
 
# 赋值或更改单元格内容
sh1['A2'] = 'dongli'
 
# 获取和更改工作表的名字
sh1.title = '成绩单'
 
# 获取成绩大于70的到sheet2 方法一
sh2 = xls['Sheet2']
index = 2
for cell_text in sh1.rows:
    if cell_text[0].coordinate != 'A1' and cell_text[1].value>70:
        sh2['A'+str(index)] = cell_text[0].value
        sh2['B'+str(index)] = cell_text[1].value
        index += 1

import openpyxl
from openpyxl.styles import Font  # 导入单元格样式
 
xls = openpyxl.load_workbook('dongli.xlsx')
sh1 = xls.active
sh2 = xls['Sheet2']
 
# 获取成绩大于70的到sheet2 方法二
for line in range(2, sh1.max_row):
    rows = sh1.cell(row=line, column=2).value
    colu = sh1.cell(row=line, column=1).value
    if rows > 70:
        sh2['A'+str(line)] = colu
        sh2['B'+str(line)] = rows
 
#  Excel 公式的使用
sh1['B7'] = '=average(b2:b6)'
 
#  设置单元格样式
font = Font(bold=True)
sh1['A7'].font = font
sh1['A7'] = '平均成绩'
 
xls.save('donglili.xls')
Python PDF操作
import PyPDF2
 
#  打开PDF并读取到内存中
pdf_obj = open('dongli.pdf', 'rb')
pdf = PyPDF2.PdfFileReader(pdf_obj)
 
#  查看PDF文件页数及内容
page_num = pdf.numPages
pdf_page = pdf.getPage(1)
page_cont = pdf_page.extractText()
pdf_obj.close()
 
#  PDF文件加密
with open('dongli.pdf', 'rb') as f_r:
    pdf = PyPDF2.PdfFileReader(f_r)
    pdf_w = PyPDF2.PdfFileWriter()
    for page_num in range(pdf.numPages):
        pdf_w.addPage(pdf.getPage(page_num))
    pdf_w.encrypt('dongli')
    with open('dongli-2.pdf', 'wb') as f_w:
        pdf_w.write(f_w)
 
#  PDF文件解密
with open('dongli-2.pdf', 'rb') as f:
    pdf = PyPDF2.PdfFileReader(f)
    if pdf.isEncrypted:
         
        pdf.decrypt('dongli')
        print(pdf.getPage(0).extractText())
 
# PDF文件加水印
with open('dongli.pdf', 'rb') as f1:
    with open('shuiyin.pdf', 'rb') as f2:
        pdf1 = PyPDF2.PdfFileReader(f1)
        pdf2 = PyPDF2.PdfFileReader(f2)
        pdfw = PyPDF2.PdfFileWriter()
 
        for num in range(pdf1.numPages):
            pdf1_page = pdf1.getPage(num)
            pdf2_page = pdf2.getPage(0)
            pdf1_page.mergePage(pdf2_page)
            pdfw.addPage(pdf1_page)
    with open('dongli-3.pdf', 'wb') as f_in:
        pdfw.write(f_in)


"""处理中文"""
from pdfminer.pdfinterp import PDFResourceManager, process_pdf 
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams 
from io import StringIO
 
 
def convert_pdf(path):
    rsrcmgr = PDFResourceManager() 
    retstr = StringIO()
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, laparams=laparams) 
    fp = open(path, 'rb')
    process_pdf(rsrcmgr, device, fp) 
    fp.close()
    device.close()
    out = retstr.getvalue() 
    retstr.close()
    return out
 
a = convert_pdf('dongli.pdf')
print(a)
Python Email 操作
import smtplib
from smtplib import SMTP_SSL
from email.header import Header
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email import encoders
 
 
def get_pwd():
    return 'rpnrsmptllbabcfd1'
 
 
smtp = SMTP_SSL("smtp.qq.com")
smtp.ehlo("smtp.qq.com")
smtp.set_debuglevel(1)
smtp.login("768865545@qq.com", get_pwd())
 
 
def send_mail():
    msg = MIMEText("测试邮件-重写", "plain", "utf-8")
    msg["Subject"] = Header("测试邮件", "utf-8")
    msg["from"] = "768865545@qq.com"
    msg["to"] = "93664045@qq.com"
 
    smtp.sendmail("768865545@qq.com", "93663045@qq.com", msg.as_string())
    smtp.close()
 
 
def send_mail_multipart(body, attachment):
    msg = MIMEMultipart()
 
    msg["subject"] = Header("测试邮件带附件", "utf-8")
    msg["from"] = "768865545@qq.com"
    msg_to = ["93663045@qq.com", "sublime11@qq.com"]
    msg["to"] = ','.join(msg_to)
 
    msg.attach(MIMEText(body, "plain", "utf-8"))
 
    with open(attachment, 'rb') as f:
        mime = MIMEBase("text", "txt", filename=attachment)
        mime.add_header(
            "Content-Disposition", "attachment", filename=attachment)
        mime.set_payload(f.read())
        encoders.encode_base64(mime)
        msg.attach(mime)
 
    smtp.sendmail("768865545@qq.com", "93663045@qq.com", msg.as_string())
    smtp.close()
 
 
def mail_all(body, type="plain", attachment=None):
    msg = MIMEMultipart()
    msg["subject"] = Header("测试邮件全部ALL--!", "utf-8")
    msg["from"] = "768865545@qq.com"
    msg_to = ["93663045@qq.com", "sublime11@qq.com"]
    msg["to"] = ','.join(msg_to)
 
    msg.attach(MIMEText(body, type, "utf-8"))
 
    if attachment:
        with open(attachment, 'rb') as f:
            mime = MIMEBase("text", "txt", filename=attachment)
            mime.add_header(
                "Content-Disposition", "attachment", filename=attachment)
            mime.set_payload(f.read())
            encoders.encode_base64(mime)
            msg.attach(mime)
     
    smtp.sendmail("768865545@qq.com", "93663045@qq.com", msg.as_string())
    smtp.close()
 
# mail_all("带附件测试三", attachment=r"e:\py\test.pkl")
 
html = """
    <html>
        <head>
            <title>这是一个测试</title>
        </head>
        <body>
            
<h1>这是一个测试</h1>

            
<h2>这是一个测试</h2>

            
<h3>这是一个测试</h3>

            
<h4>这是一个测试</h4>

            
<h5>这是一个测试</h5>

            
<h6>这是一个测试</h6>

        </body>
    </html>
 
"""
 
mail_all(html, type="html")
Python 图片处理
from PIL import ImageColor
from PIL import Image
from PIL import ImageEnhance
from PIL import ImageDraw
from PIL import ImageFont
import os

img = Image.open('banner.jpg')  # 查看图片信息
h, w = img.size
img.mode
img.format
img.getbands()
img.getpixel((1,1))

img_thumb = img.thumbnail((h//2, w//2))  # 图像缩略图
img.save('banner-1.jpg')
img.show()

img_resize = img.resize((h//3,2//3))  # 图像调整大小
img_resize.show()

enh = ImageEnhance.Contrast(img)  # 图像增强效果
enh.enhance(1.3).show()

img_crop = img.crop((100,100,400,400))  # 图像裁剪
img_crop.save('bananer-2.jpg')

img.rotate(90).show()  # 图像旋转
img.transpose(Image.FLIP_LEFT_RIGHT).show()  # 图像倒置
img.transpose(Image.FLIP_TOP_BOTTOM).show()

img_source = Image.open('banner.jpg')  # 图片加水印
img_logo = Image.open('logo.jpg')

sourc_h, source_w = img_source.size
logo_h, logo_w = img_logo.size

img_logo_copy = img_logo.copy()
img_source.paste(img_logo_copy, (sourc_h-logo_h,source_w-logo_w))
img_source.show()


new_img = Image.new('RGBA', (500, 500), 'white')  # 创建图像
draw_img = ImageDraw.Draw(new_img)
draw_img.text((50, 50), 'TEXT', fill='red')
new_img.save('Test.png')

font_path = os.path.join(r'c:\windows\Fonts','simhei.ttf') # 创建带中文字体的图像
font = ImageFont.truetype(font_path, 40)

new_img = Image.new('RGBA', (500, 500), 'white')
draw_img = ImageDraw.Draw(new_img)
draw_img.text((100, 100),'董礼', fill='red', font=font)
new_img.save('t1.png')

最后更新于:2018-07-11 20:42:50