高效办公

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

1.

群发送邮件
# 导入所需模块
import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

# 邮箱帐号和授权码,连接和登录邮箱
mailUser = "aLing@qq.com"
mailPass = "abcnawckdujkdace"
smtpObj = smtplib.SMTP_SSL("smtp.qq.com", 465)
smtpObj.login(mailUser, mailPass)

# 发件人、收件人
sender = "aLing@qq.com"
receiverDict = {"xixi":"adc@yequ.com",
"kiki":"def@yequ.com","tongtong":"yza@yequ.com"}

# 文件路径
path = "/Users/aLing"

for receiver in receiverDict:


# 编辑并整合发件人、收件人、主题信息
message = MIMEMultipart()
message["From"] = Header(f"阿玲<{sender}>")
message["To"] = Header(f"{receiver}<{receiverDict[receiver]}>")
message["Subject"] = Header(f"{receiver}-年会邀请函")

# 编辑邮件正文
mailContent = MIMEText(f"Dear {receiver} 邀请你参加年会", "plain", "utf-8")

# 读取图片文件
filePath = path + "/" + receiver + ".jpg"
with open(filePath, "rb") as imageFile:
fileContent = imageFile.read()

# 编辑附件信息
att = MIMEImage(fileContent)
att.add_header("Content-Disposition", "attachment", filename="邀请函.jpg")

# 整合正文和图片
message.attach(mailContent)
message.attach(att)
# 发送邮件
smtpObj.sendmail(sender, receiverDict[receiver], message.as_string())
print("发送成功")

2 桌面文件整理
import os
import shutil
desktoppath="D:\桌面\yequ\Downloads"
# 使用 os.listdir()函数获取该路径下所有的文件(夹),并赋值给变量 allItems
allitems = os.listdir(desktoppath)
# 使用 for 循环遍历所有文件(夹)
for item in allitems:
# 获取文件后缀名
extension = os.path.splitext(item)[1].lower()
targetpath=""
if extension in [".jpg", ".jpeg", ".gif", ".png", ".bmp"]:
# 使用 os.path.join()函数拼接分类文件夹路径:图片文件
# 并赋值给变量 targetPath
targetpath = os.path.join(desktoppath, "图片文件")
elif extension in [".avi", ".mp4", ".wmv", ".mov", ".flv"]:
# 使用 os.path.join()函数拼接分类文件夹路径:视频文件
# 并赋值给变量 targetPath
targetpath = os.path.join(desktoppath, "视频文件")
elif extension in [".wav", ".mp3", ".mid", ".ape", ".flac"]:
# 使用 os.path.join()函数拼接分类文件夹路径:音频文件
targetpath = os.path.join(desktoppath, "音频文件")
elif extension in [".pdf"]:
# 使用 os.path.join()函数拼接分类文件夹路径:PDF 文件
targetpath = os.path.join(desktoppath, "PDF 文件")
elif extension in [".docx", ".doc"]:
# 使用 os.path.join()函数拼接分类文件夹路径:Word 文件
targetpath = os.path.join(desktoppath, "Word 文件")
elif extension in [".xlsx", ".xls"]:
# 使用 os.path.join()函数拼接分类文件夹路径:Excel 文件
targetpath = os.path.join(desktoppath, "Excel 文件")
elif extension in [".pptx", ".ppt"]:
# 使用 os.path.join()函数拼接分类文件夹路径:PPT 文件
targetpath = os.path.join(desktoppath, "PPT 文件")
else:
# 使用 os.path.join()函数拼接分类文件夹路径:其他文件
targetpath = os.path.join(desktoppath, "其他文件")
# 判断当如果目标文件夹不存在
if not os.path.exists(targetpath):
# 使用 os.mkdir()函数创建文件夹
os.mkdir(targetpath)

# 使用 os.path.join()函数拼接 desktopPath 和文件名


# 并赋值给变量 itemPath
itempath = os.path.join(desktoppath, item)

# 判断当 itemPath 不是文件夹时。


if not os.path.isdir(itempath):
# 使用 shutil.move()函数移动文件到 targetPath 路径
shutil.move(itempath, targetpath)

3.Excel 文档读取
# 导入 openpyxl 模块
import openpyxl

# 将计算单月销售额的步骤移到函数 getMonthlySold 中
# 获取单月“麻辣味口香糖”销售额的函数
# 参数 filePath: 销售数据 Excel 文件路径
# 返回值: 计算出的销售额结果
def getMonthlySold(filePath):
# 使用 openpyxl.load_workbook()函数读取工作簿,文件路径使用函数参数 filePath
# 添加 data_only=True 打开工作簿,获取公式计算后的值
wb = openpyxl.load_workbook(filePath, data_only=True)

# 通 过 工 作 簿 对 象 wb 获 取 名 为 “ 销 售 订 单 数 据 ” 的 工 作 表 对 象 , 并 赋 值 给 变 量
orderSheet
orderSheet = wb["销售订单数据"]

# 定义一个变量 gumSold 用来表示本月“麻辣味口香糖”的销售金额


gumSold = 0

# 遍历工作表的所有行数据
for rowData in orderSheet.rows:
# 商品名 C 列是第 3 列,索引也就是 2
productName = rowData[2].value
# 获取订单总价 I 列的索引和总价
priceIndex = openpyxl.utils.cell.column_index_from_string("I") - 1
price = rowData[priceIndex].value

# 判断如果 productName 是“麻辣味口香糖”


if productName == "麻辣味口香糖":
# 逐个添加总价到本月销售额(gumSold)里
gumSold = gumSold + price

# 将计算后的销售额 gumSold 返回
return gumSold

# 定义一个空列表 soldList 来逐个装入各个月份的销售额


soldList = []

# 使用 for 循环和 range,逐个遍历 1~12 的数字


# 注意:range 的第二个参数是不包括到循环内的
for month in range(1, 13):
# 利用格式化字符串拼接 Excel 文件名,传入到获取单月销售额的函数并赋值给变量
monthlySold
monthlySold = getMonthlySold(f"2019 年{month}月销售订单.xlsx")
# 将“麻辣味口香糖”单月销售额 monthlySold 使用 append 函数逐个添加到列表中
soldList.append(monthlySold)

# 使用 max()函数获取最大的销售额并赋值给变量 maxSold
maxSold = max(soldList)

# 使用 index()函数获取最大值的索引,索引值加 1 后得到月份赋值给 maxMonth 变量


maxMonth = soldList.index(maxSold) + 1

# 输出最终的结果:麻辣味口香糖在{maxMonth}月份卖得最好
print(f"麻辣味口香糖在{maxMonth}月份卖得最好")
4.excel 文档写入
# 导入 openpyxl 模块
import openpyxl

# 创建一个新工作簿
newWb = openpyxl.Workbook()

# 将默认工作表赋值给 aSheet 变量
aSheet = newWb["Sheet"]

# 将 aSheet 工作表名称修改为“A 平台”


aSheet.title = "A 平台"

# 创建 B 平台 的工作表并赋值给变量 bSheet
bSheet = newWb.create_sheet("B 平台")

# 创建 C 平台 的工作表并赋值给变量 cSheet
cSheet = newWb.create_sheet("C 平台")
# 使用 for 循环遍历工作簿对象的 worksheets 属性
for sheet in newWb.worksheets:
# 给每一个工作表设置表头
sheet["A1"].value = "商品名"
sheet["B1"].value = "月份"
sheet["C1"].value = "销售额"

# 计算月份工作簿内各个商品的总价,并添加数据到汇总工作表
# 参数 filePath: 工作簿文件路径
# 参数 orderSheetName: 订单工作表的名称
# 参数 nameIndex: 商品名称的列索引
# 参数 nameHead: 商品名称的表头
# 参数 priceColumn: 总价的列号
# 参数 month: 当前处理的月份
# 参数 targetSheet: 要添加到的目标工作表
def processMonthFile(filePath, orderSheetName, nameIndex, nameHead, priceColumn, month,
targetSheet):
# 定义一个全局变量存放工作簿
global wb
# 定义全局变量工作表名称 orderSheet
global orderSheet
# 定义一个全局变量空字典用来放本月数据
global monthData
monthData = {}
# 定义一个全局变量存放数据元组
global rowData

# 使用 load_wordbook 函数读取工作簿
wb = openpyxl.load_workbook(filePath, data_only=True)
# 获取订单工作表
orderSheet = wb[orderSheetName]

# 定义一个空字典用来放本月数据
monthData = {}

# 遍历订单工作表,计算每个商品的总销售额
for row in orderSheet.rows:
# 获取订单商品名称
productName = row[nameIndex].value
# 跳过表头
if productName == nameHead:
continue
# 获取总价列的索引
priceIndex = openpyxl.utils.cell.column_index_from_string(priceColumn) - 1
# 获取订单总价
orderPrice = row[priceIndex].value

# 先安全地获取已经统计到的商品月销售额赋值给 monthPrice
# 如果还不在字典中,返回 0
monthPrice = monthData.get(productName, 0)
# 将这个订单的价格累加到商品总价
monthData[productName] = monthPrice + orderPrice

# 遍历本月数据字典的 keys,也就是商品名称
for productName in monthData.keys():
# 按顺序构造行数据元组: 商品名, 月份, 销售额数据
rowData = (productName, f"{month}月份", monthData[productName])
# 使用 append()函数将 rowData 添加到目标工作表中
targetSheet.append(rowData)

# 使用 for 循环和 range,逐个遍历 1~12 的数字


for month in range(1, 13):
# 使用 processMonthFile 函数,汇总 A 平台数据
# 格式化输出 A 平台文件路径:A 平台/2019XX.xlsx,其中 XX 是月份
processMonthFile(f"A 平台/2019{month:02}.xlsx","明细",4,"名称","F",month,aSheet)
# 汇总 B 平台数据
processMonthFile(f"B 平 台 /order_2019_{month}.xlsx"," 订 单 详 情 ",1," 商 品 名
称","G",month,bSheet)
# 汇总 C 平台数据
processMonthFile(f"C 平 台 /2019 年 {month} 月 销 售 订 单 .xlsx"," 销 售 订 单 数 据 ",2," 商 品
名","I",month,cSheet)

# 将工作簿保存到路径 /Users/yequ/data/汇总.xlsx
newWb.save("/Users/yequ/data/汇总.xlsx")

5. word 读取
# 使用 import 导入 os 模块
import os
# 使用 import 导入 docx
import docx
# 使用 import 导入 openpyxl 模块
import openpyxl

# 第一大题选择题标准答案
standardOne = ['B', 'B', 'B', 'C', 'D', 'A', 'D', 'D', 'B', 'A']
# 第二大题填空题标准答案
standardTwo = ["东临碣石", "行舟绿水前", "孤山寺北贾亭西", "断肠人在天涯", "故人具鸡
黍", "一曲新词酒一杯", "何当共剪西窗烛", "误入藕花深处", "烟笼寒水月笼沙", "万籁此都
寂", "初日照高林", "腾蛇乘雾"]

# 将乔老师的答题卡文件夹路径 /Users/qiao/answerKey 赋值给变量 allKeyPath


allKeyPath = "/Users/qiao/answerKey"
# 使用 os.listdir()函数获取该路径下所有的文件,并赋值给变量 allItems
allItems = os.listdir(allKeyPath)

# 定义一个空列表 allStudentsData 存储所有学生数据


allStudentsData = []

# 使用 for 循环逐个遍历所有学生答题卡
for item in allItems:
# 定义一个空字典 studentData 存储单个学生数据
studentData = {}

# 使用 os.path.splitext()函数获取文件名的前半段,并赋值给变量 fileName
fileName = os.path.splitext(item)[0]
# 使用 split()函数以"-"分隔文件名,将第 1 部分班级信息赋值到学生数据字典的 classInfo
键里
studentData["classInfo"] = fileName.split("-")[0]
# 使用 split()函数以"-"分隔文件名,将第 2 部分姓名信息赋值到学生数据字典的 name 键

studentData["name"] = fileName.split("-")[1]

# 使用 os.path.join()函数拼接出答题卡路径,并赋值给变量 keyPath
keyPath = os.path.join(allKeyPath, item)
# 读取答题卡并赋值给变量 doc
doc = docx.Document(keyPath)

# 读取第四段学号段,并赋值给变量 idPara
idPara = doc.paragraphs[3]
# 读取学号段中第二个样式块,并赋值给变量 idRun
idRun = idPara.runs[1]
# 读取学号,并赋值到学生数据字典的 id 键里
studentData["id"] = idRun.text

# 初始化学生数据字典里 scoreTwo 字段为 0 分,作为填空题分数


studentData["scoreTwo"] = 0

# 使用 for 循环和 enumerate()函数


# 遍历储存标准答案的列表 standardTwo 的同时
# 生成一个从 8 开始的 idx
for idx,value in enumerate(standardTwo, 8):
# 获取学生答案,并赋值给变量 studentAnswerTwo
studentAnswerTwo = doc.paragraphs[idx].runs[1].text
# 判断当学生答案与标准答案相等时
if studentAnswerTwo == value:
# 当学生答案与标准答案一样时,学生的填空题分数加 5 分
studentData["scoreTwo"] = studentData["scoreTwo"] + 5

# 读取答题卡中的表格,并赋值给变量 table
table = doc.tables[0]
# 读取表格中的第二行,并赋值给变量 secRow
secRow = table.rows[1]
# 读取第二行中的所有单元格,并赋值给变量 secCell
secCell = secRow.cells

# 初始化学生数据字典里 scoreOne 字段为 0 分,作为选择题分数


studentData["scoreOne"] = 0

# 使用 for 循环和 enumerate()函数


# 遍历储存标准答案的列表 standardOne 的同时
# 生成一个从 0 开始的 idx
for idx,value in enumerate(standardOne):
# 获取学生选择题答案,并赋值给变量 studentAnswerOne
studentAnswerOne = secCell[idx].text
# 判断当学生答案与标准答案相等时
if studentAnswerOne == value:
# 当学生答案与标准答案一样时,学生的选择题分数加 5 分
studentData["scoreOne"] = studentData["scoreOne"] + 5

# 使用 append()函数将 studentData 添加到总学生数据 allStudentsData 中


allStudentsData.append(studentData)

# 创建一个新工作簿,并赋值给变量 newWb
newWb = openpyxl.Workbook()
# 将名为 Sheet 的默认工作表赋值给变量 sheet
sheet = newWb["Sheet"]
# 将 sheet 工作表名称修改为"成绩表"
sheet.title = "成绩表"

# 给工作表设置表头
sheet["A1"].value = "学生姓名"
sheet["B1"].value = "学生班级"
sheet["C1"].value = "学生学号"
sheet["D1"].value = "选择题分数"
sheet["E1"].value = "填空题分数"
# 遍历所有学生数据和对应的索引 index
for index, studentData in enumerate(allStudentsData):
# 设置学生姓名
sheet[f"A{index+2}"].value = studentData["name"]
# 设置学生班级
sheet[f"B{index+2}"].value = studentData["classInfo"]
# 设置学生学号
sheet[f"C{index+2}"].value = studentData["id"]
# 设置选择题分数
sheet[f"D{index+2}"].value = studentData["scoreOne"]
# 设置填空题分数
sheet[f"E{index+2}"].value = studentData["scoreTwo"]

# 使用 save()函数将工作簿保存到指定路径
newWb.save("/Users/qiao/answerKey/成绩汇总.xlsx")

6. word 写入
# 使用 import 导入 openpyxl
import openpyxl

# 使用 import 导入 docx
import docx

# 定义一个新函数 replaceInfo,包含参数 doc,oldInfo,newInfo


def replaceInfo(doc, oldInfo, newInfo):
# 遍历 Word 文件中的所有段落
for paragraph in doc.paragraphs:
# 遍历所有段落中的所有样式块
for run in paragraph.runs:
# 用.replace()方法,将样式块文本需要被替换的旧字符串 oldInfo,替换成新字符串
newInfo
run.text = run.text.replace(oldInfo, newInfo)
# 遍历 Word 文件中的所有表格
for table in doc.tables:
# 遍历所有表格中的所有行
for row in table.rows:
# 遍历所有行中的所有单元格
for cell in row.cells:
# 用.replace()方法,将单元格文本需要被替换的旧字符串 oldInfo,替换成新字符
串 newInfo
cell.text = cell.text.replace(oldInfo, newInfo)

# 添加 data_only = True,读取工作目录里名为"夜曲大学英语考试成绩.xlsx"的工作簿并赋值
给变量 wb
wb = openpyxl.load_workbook("夜曲大学英语考试成绩.xlsx",data_only = True)

# 通过工作簿对象 wb 获取名为“汇总”的工作表对象,并赋值给变量 ws
ws = wb["汇总"]

# 为表头定义一个空的元组并赋值给变量 firstRow
firstRow = ()

# 遍历工作表的所有行和其对应的索引
# 用变量 rowIndex 表示索引,变量 row 表示每一行
for rowIndex, row in enumerate(ws.rows):
# 判断是第一行时
if rowIndex == 0:
# 将第一行数据赋值给变量 firstRow
firstRow = row
# 非第一行数据时
else:
# 读取模板 Word 文档:成绩报告单模版.docx 并赋值给变量 doc
doc = docx.Document("成绩报告单模版.docx")
# 遍历每个单元格和对应的列索引
# 用变量 columnIndex 表示索引,cell 表示单元格
for columnIndex, cell in enumerate(row):
# 将该单元格对应列的表头使用 columnIndex 提取出
# 并赋值给变量 oldInfo
oldInfo = firstRow[columnIndex].value
# 将单元格的值使用 str()函数转换成字符串
# 并赋值给变量 newInfo
newInfo = str(cell.value)
# 使用 replaceInfo()函数替换 doc 文档内容
replaceInfo(doc, oldInfo, newInfo)
# 提取每行第一列的学生姓名,并赋值给变量 name
name = row[0].value
# 将 doc 文档保存在 学生成绩单 文件夹下,文件名格式为"成绩报告单_{姓名}.docx"
doc.save(f"学生成绩单/成绩报告单_{name}.docx")

7. pdf 改写:
# 使用 import 导入 os 模块
import os

# 使用 import 导入 pdfplumber 模块
import pdfplumber

# 使用 import 导入 openpyxl 模块
import openpyxl
# 创建一个新工作簿赋值给变量 newWb
newWb = openpyxl.Workbook()

# 将名为 Sheet 的默认工作表赋,值给 sheet 变量


sheet = newWb["Sheet"]

# 将 PDF 文件夹路径 /Users/acheng/Desktop/银行账单,赋值给变量 path


path = "/Users/acheng/Desktop/银行账单"

# 使用 os.listdir()函数获取该路径下所有的文件名称,并赋值给变量 allItems
allItems = os.listdir(path)

# 使用 for 循环遍历 allItems


for item in allItems:

# 使用 os.path.join()函数拼接 pdf 文件路径,赋值给 pdfPath


pdfPath = os.path.join(path, item)

# 读取 PDF 文档,并赋值给 pdf


pdf = pdfplumber.open(pdfPath)

# 使用 for 循环遍历 pdf 页面列表


for page in pdf.pages:

# 使用 extract_tables()函数,提取页面中的所有表格
# 并将第一个表格赋值给 tableData
tableData = page.extract_tables()[0]

# 遍历列表 tableData
for row in tableData:

# 将表格每一行的数据添加到工作表中
sheet.append(row)

# 格式化输出 XX 提取完成
print(f"{item}提取完成")

# 将工作簿保存到路径 /Users/acheng/Desktop/账单合集.xlsx
newWb.save("/Users/acheng/Desktop/账单合集.xlsx")

8. 办公室综合应用:
# 使用 import 导入 smtplib 模块
import smtplib
# 使用 from..import 导入邮件正文内容数据处理模块
from email.mime.text import MIMEText
# 使用 from..import 邮件协议的协议头模块
from email.header import Header
# 使用 import 导入 openpyxl 模块
import openpyxl

# 邮箱服务器设置,赋值给 mailHost
mailHost = "smtp.qq.com"
# 邮箱账号设置,赋值给 mailUser
mailUser = "ahuayequ@qq.com"
# 邮箱授权码设置赋值给 mailPass
mailPass = "wiscbwlrcodprabd"

# 读取"/Users/ahua/汇总.xlsx"路径下的工作簿
wb = openpyxl.load_workbook("/Users/ahua/汇总.xlsx")
# 读取"面试教师名单"工作表,赋值给 nameSheet
nameSheet = wb["面试教师名单"]
# 定义一个字典用于存储教师邮箱,赋值给 teacherMail
teacherMail = {}

# 循环查找获取邮箱,追加到邮箱中
for rowData in nameSheet.rows:
# 取每行第 1 个数据姓名赋值给 name
name = rowData[0].value
# 取每行第 11 个数据邮箱赋值给 mail
mail = rowData[10].value
# 按照 name:mail 的方式写入字典中
teacherMail[name] = mail

# 使用 smtplib.SMTP_SSL(服务器, 端口号),端口号为 465,赋值给 smtpObj


smtpObj= smtplib.SMTP_SSL(mailHost, 465)
# 使用 login()函数传入邮箱账户和授权码,登录邮箱
smtpObj.login(mailUser, mailPass)

# 将发送者邮箱赋值给 sender
sender = mailUser

# 将字典转换成可遍历的列表,并赋值给 receiverList
receiverList = teacherMail.items()

# 遍历 receiverList
for item in receiverList:
# 取第一个元素也就是姓名赋值给变量 name
name = item[0]
# 取第二个元素也就是收件人邮箱给变量 receiver
receiver = item[1]
# 判断当变量 name 等于"姓名"时
if name == "姓名":
# 跳过本次循环
continue
# 邮件正文
message = MIMEText(f"{name}老师您好,恭喜您通过夜曲大学的筛选,现邀请您参加面
试", "plain", "utf-8")
# 邮件主题
message["Subject"] = Header("夜曲大学面试邀请通知")
# 邮件发件人名称
message["From"] = Header(f"夜曲大学教务处 <{sender}>")
# 邮件收件人名称
message["To"] = Header(f"{name}老师 <{receiver}>")
# 使用 sendmail(发送人,收件人,message.as_string())发邮件
smtpObj.sendmail(sender, receiver, message.as_string())
# 获取姓名输出“xx 邮件发送成功”
print(f"{name}邮件发送成功")

9. 照片:
# 导入 os 模块
import os

# 导入 ezexif 模块
import ezexif

# 导入 shutil 模块
import shutil

# 使用 os.chdir()函数修改当前工作目录到/Volumes/yequ
os.chdir('/Volumes/yequ')

# 照片的相对路径
yequPhotoPath = "照片"

# 使用函数 os.listdir()获取所有待处理照片文件列表
photoList = os.listdir(yequPhotoPath)

# 遍历文件列表
for photo in photoList:
# 使用 os.path.join()函数组合得到照片文件路径,并赋值给变量 photoPath
photoPath = os.path.join(yequPhotoPath, photo)
# 获取 exif 信息
exifInfo = ezexif.process_file(photoPath)
# 获取拍摄时间
takeTime = exifInfo["EXIF DateTimeOriginal"]
# 通过空格分隔成拍摄日期和拍摄时间
takeTimeParts = takeTime.split(" ")
# 分隔后的字符串列表第一个元素就是拍摄日期,赋值给变量 photoDate
photoDate = takeTimeParts[0]
# 再把拍摄日期通过冒号分隔,分成年、月、日三部分,赋值给变量 photoDateParts
photoDateParts = photoDate.split(":")

# 利用格式化字符串拼出文件夹名称
targetFolderName = f"{photoDateParts[0]}年{photoDateParts[1]}月"
# 使用 os.path.join()函数拼出分类文件夹的路径, 并赋值给 photoTargetPath 变量
photoTargetPath = os.path.join(yequPhotoPath, targetFolderName)

# 如果目标文件夹不存在,使用 os.mkdir()函数创建文件夹
if not os.path.exists(photoTargetPath):
os.mkdir(photoTargetPath)

# 移动到目标文件夹
shutil.move(photoPath, photoTargetPath)

You might also like