目錄
一 python辦公自動化所需類庫
二 python操作excel文件
三 python自動發(fā)送郵件
四 python操作word文件
五 python操作PPT文件文章來源:http://www.zghlxwxcb.cn/news/detail-454962.html
一 python辦公自動化所需類庫
python操作excel、word、ppt所需庫如下,文章來源地址http://www.zghlxwxcb.cn/news/detail-454962.html
import xlrd3 # 讀取表格
import xlwt # 寫入工作表
import xlsxwriter # 支持大文件寫入工作表
import smtplib # 郵件發(fā)送
# 郵件發(fā)送格式擴展
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# ppt操作
from docx import Document
from docx.shared import Pt, RGBColor
from docx.enum.style import WD_STYLE_TYPE
from docx.enum.text import *
# word轉(zhuǎn)pdf
from win32com.client import constants, gencache
import os # 系統(tǒng)常用操作
import random
import pptx # 操作ppt
from pptx.util import Inches, Pt
from pptx.enum.shapes import MSO_SHAPE # 不影響程序運行
from pptx.dml.color import RGBColor
from pptx.chart.data import CategoryChartData
from pptx.enum.chart import XL_CHART_TYPE
from pptx.enum.chart import XL_LEGEND_POSITION
二 python操作excel文件
# 讀取excel文件
# data = xlrd3.open_workbook('data.xlsx')
# load=data.sheet_loaded(0) #加載第一個工作表,卸載工作表使用sheet_loaded(0)
# print(load)
# print(data)
# d2=data.sheets()
# print(d2) #根據(jù)索引獲取工作表
# print(data.sheet_by_name('Sheet1') )#根據(jù)名字獲取工作表
# print(data.sheet_names()) #獲取所有工作表的名稱
# print(data.nsheets) #工作表的個數(shù)
# 操作行
# sheet=data.sheet_by_index(0) #獲取工作表
# print(sheet.nrows) #獲取有效行
# print(sheet.row(1)) #第一行的內(nèi)容
# print(sheet.row_types(2)) #數(shù)據(jù)類型,2表示數(shù)字
# print(sheet.row(1)[2].value) #獲取單元格的值
# print(sheet.row_values(1)) #獲取指定行的單元格的值
# print(sheet.row_len(1)) #獲取單元格的長度
# 操作列
# sheet=data.sheet_by_index(0)
# print(sheet.nrows) #列數(shù)
# print(sheet.col(1)) #指定列的內(nèi)容
# print(sheet.col(1)[1].value) #指定列的單元格內(nèi)容
# print(sheet.col_values(1)) #第一列的內(nèi)容
# print(sheet.col_types(1) ) #指定列的數(shù)據(jù)類型
# 操作單元格
# sheet=data.sheet_by_index(0)
# print(sheet.cell(1,1)) #獲取指定行列的數(shù)據(jù)類型
# print(sheet.cell_type(1,2)) #獲取指定單元格的數(shù)據(jù)類型
# print(sheet.cell(1,1).ctype) #獲取指定單元格的數(shù)據(jù)類型
# print(sheet.cell(1,1).value) #獲取值
# print(sheet.cell_value(1,1)) #獲取指定單元格的內(nèi)容
# 初始化字體屬性
# titlestyle = xlwt.XFStyle()
#
# # 設置字體
# titlefont = xlwt.Font()
# titlefont.name = '宋體'
# titlefont.bold = True
# titlefont.height = 11 * 20
# titlefont.colour_index = 0x80
# titlestyle.font = titlefont
#
# # 單元格對齊方式
# cellalient = xlwt.Alignment()
# cellalient.horz = 0x02
# cellalient.vert = 0x01
# titlestyle.alignment = cellalient
#
# # 邊框
# borders = xlwt.Borders()
# borders.right = xlwt.Borders.DASHED
# borders.bottom = xlwt.Borders.DOTTED
# titlestyle.borders = borders
#
# # 背景顏色
# datastyle = xlwt.XFStyle()
# bgcolor = xlwt.Pattern()
# bgcolor.pattern = xlwt.Pattern.SOLID_PATTERN
# bgcolor.pattern_fore_colour = 22 # 背景顏色
# datastyle.pattern = bgcolor
#
# # 寫入excel
# wb = xlwt.Workbook() # 表對象
# ws = wb.add_sheet('wsb') # 添加工作表
# ws.write_merge(0, 1, 0, 5, '貨幣兌換表', titlestyle) # 添加內(nèi)容,0、1是行,0、5是列范圍,titlestyle為字體樣式
#
# data = (('05', 1, 2, 3, 3), ('06', 2, 1, 1, 4)) # 使用元組保存需要存儲的數(shù)據(jù)
#
# # 遍歷元組寫入內(nèi)容
# for i, item in enumerate(data):
# for j, val in enumerate(item):
# if j == 0:
# ws.write(i + 2, j, val, datastyle) # 以單元格的方式循環(huán)寫入,datastyle為自定義的樣式
# else:
# ws.write(i + 2, j, val) # 以單元格的方式循環(huán)寫入
#
# # 創(chuàng)建第二個工作表
# wsimage = wb.add_sheet('image')
# # 寫入圖片: 參數(shù)含義為圖片名稱,行列
# # wsimage.insert_bitmap('a.jpg', 0, 0) #不支持png或jpg格式的圖片
#
#
# wb.save('2022.xls') # 保存數(shù)據(jù),創(chuàng)建工作表,只支持xls格式
# 支持大文件寫入模塊xlsxwriter的基本使用
# wb = xlsxwriter.Workbook('data.xlsx') # 獲得文件對象
# cell_format = wb.add_format({'bold': True}) # 通過字典設置格式化對象
#
# # 通過對象格式化對象
# cell_format1 = wb.add_format()
# cell_format1.set_bold() # 設置加粗
# cell_format1.set_font_color('red') # 顏色
# cell_format1.set_font_size(14) # 字體大小
# cell_format1.set_align('center') # 居中顯示
#
# cell_format2 = wb.add_format()
# cell_format2.set_bg_color('00FFFF') # 設置背景顏色
#
# sheet = wb.add_worksheet('newsheet') # 創(chuàng)建工作表
# # 寫入
# sheet.write(0, 0, '2022年', cell_format1)
# sheet.merge_range(1, 0, 2, 2, '銷售數(shù)據(jù)') # 合并單元格
#
# # 數(shù)據(jù)
# dt = (
# ['一月', 100, 200],
# ['二月', 140, 270],
# ['三月', 190, 210]
# )
#
# # 寫入行
# sheet.write_row(3, 0, ['月份', '預期銷售額', '實際銷售額'], cell_format2)
# # 遍歷并寫入數(shù)據(jù)
# for index, item in enumerate(dt):
# sheet.write_row(index + 4, 0, item)
# # 寫入excel公式,計算結(jié)果
# sheet.write(7, 1, '=sum(B5:B7)')
# sheet.write(7, 2, '=sum(C5:C7)')
# # 寫入鏈接
# sheet.write_url(9, 0, 'https://www.imooc.com/course/list?c=python', string='更多數(shù)據(jù)')
# # 寫入圖片
# sheet.insert_image(10, 0, 'Qt.png')
#
# # 寫入圖表
# chart = wb.add_chart({'type': 'column'})
# chart.set_title({'name': '第一季度生產(chǎn)統(tǒng)計'})
# # X,Y描述信息
# chart.set_x_axis({'name': '月份'})
# chart.set_y_axis({'name': '生產(chǎn)統(tǒng)計'})
# # 數(shù)據(jù)
# chart.add_series({
# 'name': '預期生產(chǎn)',
# '月份': '=newsheet!$A&5:&A&7',
# 'values': ['newsheet', 4, 1, 6, 1],
# 'data_labels': {'value': True} #顯示數(shù)據(jù)標簽
# })
# chart.add_series({
# 'name': '實際生產(chǎn)',
# '月份': '=newsheet!$A&5:&A&7',
# 'values': ['newsheet', 4, 2, 6, 2],
# 'data_labels': {'value': True}
# })
# sheet.insert_chart('A43', chart)
#
# wb.close()
三 python自動發(fā)送郵件
# 郵件發(fā)送地址
# host_server = 'smtp.qq.com' # 主機地址
# sender = '1234@qq.com' # 發(fā)件人郵箱
# code = 'dfsfsdfsd' # 郵箱授權碼
# user1 = '1222@qq.com' # 收件人
#
# # 郵件數(shù)據(jù)
# mail_title = '2月平均收入' # 郵件標題
# mail_content = '1月平均收入,請查看附件' # 內(nèi)容
# attachment = MIMEApplication(open('data.xlsx', 'rb').read()) # 附件
# attachment.add_header('Content-Disposition', 'attachment', filename='data.xlsx') # 附件屬性
#
# smtp = smtplib.SMTP(host_server) # SMTP
# smtp.login(sender, code) # 登錄
# # 發(fā)送
# msg = MIMEMultipart() # 帶附件的實例
# msg['Subject'] = mail_title
# msg['From'] = sender
# msg['To'] = user1
# msg.attach(MIMEText(mail_content))
# msg.attach(attachment)
# smtp.sendmail(sender, user1, msg.as_string())
四 python操作word文件
# docment = Document() # 創(chuàng)建文檔對象
# docment.add_heading('wsb簡述', level=4) # 寫入內(nèi)容,指定標題級別
#
# # 樣式
# style = docment.styles.add_style('textstyle', WD_STYLE_TYPE.PARAGRAPH) # 給段落設置樣式
# print(style.style_id) # 打印樣式id
# print(style.name) # 打印樣式名稱
# style.font.size = Pt(5) # 字體大小
#
# #刪除樣式
# #docment.styles['textstyle'].delete()
#
# # 段落
# p1 = docment.add_paragraph('這是一個非常努力的小伙子,值得信賴', style='textstyle')
# p1.insert_paragraph_before('hello') # 插入段落
# # 段部落格式
# format = p1.paragraph_format
# format.left_indent = Pt(20) # 左側(cè)縮進
# format.right_indent = Pt(20) # 右側(cè)縮進
# format.first_line_indent = Pt(20) # 首行縮進
# format.line_spacing = 1.5 # 行間距
#
# run = p1.add_run('hello world hello python')
# run1 = p1.add_run('python是一門有趣的語言')
#
# # 字體、字號、文字顏色
# run.font.size = Pt(12)
# run.font.name = '微軟雅黑'
# run.font.color.rgb = RGBColor(235, 33, 24)
#
# # 加粗、下劃線、斜體
# run1.bold = True
# run1.font.underline = True
# run1.font.italic = True
#
# # 插入圖片:指定長寬
# docment.add_picture('a.jpg', Pt(50), Pt(50))
# # 插入表格
# table = docment.add_table(rows=1, cols=3, style='Medium List 2') # 1行三列
# header_cells = table.rows[0].cells
# header_cells[0].text = '月份'
# header_cells[1].text = '預期'
# header_cells[2].text = '實際'
# # 數(shù)據(jù)
# data = (
# ['一月', 200, 100],
# ['二月', 600, 300],
# ['三月', 800, 900]
# )
# # 寫入數(shù)據(jù)
# for item in data:
# rows_cells = table.add_row().cells
# rows_cells[0].text = item[0]
# rows_cells[1].text = str(item[1])
# rows_cells[2].text = str(item[2])
#
# # 獲取表格
# print(len(docment.tables[0].rows)) # 行數(shù)
# print(len(docment.tables[0].columns)) # 列數(shù)
# print(docment.tables[0].cell(0, 2).text) # 單元格內(nèi)容
#
# docment.save('wsb.docx') # 保存文檔并指定文件的名稱
# word轉(zhuǎn)PDF
# def createpdf(wordPath, pdfPath):
# word = gencache.EnsureDispatch('Word.Application')
# doc = word.Documents.Open(wordPath, ReadOnly=1)
# # 轉(zhuǎn)換方法
# doc.ExportAsFixedFormat(pdfPath, constants.wdExportFormatPDF)
# word.Quit()
#
#
# #createpdf('H:/1-DOE實驗設計-新規(guī)劃/python/python辦公自動化/wsb.docx', 'H:/1-DOE實驗設計-新規(guī)劃/python/python辦公自動化/info.pdf')
#
# # word轉(zhuǎn)PDF:多個文件的轉(zhuǎn)換
# print(os.listdir(".")) # 當前文件夾下的所有文件
# wordfiles=[]
# for file in os.listdir('.'):
# if file.endswith(('.doc','.docx')):
# wordfiles.append(file)
#
# print(wordfiles)
# for file in wordfiles:
# filepath=os.path.abspath(file)
# index=filepath.rindex('.')
# pdfpath=filepath[:index]+'.pdf'
# print(filepath)
# print(pdfpath)
# createpdf(filepath,pdfpath)
# 案例:隨機生成試卷,使用test.xlsx來生成不同的word試卷
# data = xlrd3.open_workbook('test.xlsx')
# sheet = data.sheet_by_index(0)
# print(data.nsheets)
# print(sheet.nrows)
#
# class Quesition:
# pass
#
#
# def createQuestion():
# questionlist = []
# for i in range(sheet.nrows):
# if i > 1:
# obj = Quesition()
# obj.subject = sheet.cell(i, 1).value # 題目
# obj.quesitiontype = sheet.cell(i, 2).value # 題型
# # ABCD四個選項
# obj.option = []
# obj.option.append(sheet.cell(i, 3).value)
# obj.option.append(sheet.cell(i, 4).value)
# obj.option.append(sheet.cell(i, 5).value)
# obj.option.append(sheet.cell(i, 6).value)
# # 分值
# obj.score = sheet.cell(i, 7).value
# questionlist.append(obj)
# random.shuffle(questionlist) # 隨機排序試題
# return questionlist
#
#
# # 生成word試卷
# def createPaper(filename, papername, questionlist):
# document = Document()
# # 頁眉和頁腳信息
# section = document.sections[0]
# header = section.header
# p1 = header.paragraphs[0]
# p1.text = papername
# footer = section.footer
# p2 = footer.paragraphs[0]
# p2.text = '內(nèi)部試卷,禁止泄露'
#
# # 試卷基本信息
# title = document.add_heading(papername, level=1)
# # title.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# p3 = document.paragraph()
# p3.add_run('姓名:_____')
# p3.add_run('所屬部門:_____')
# # p3.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# # 試題信息
# for quesiton in questionlist:
# subject = document.add_paragraph()
# run = subject.add_run(quesiton.subject)
# run.blod = True
# subject.add_run('[%s]分' % str(quesiton.score))
# random.shuffle(quesiton.option) # 打亂題目順序
# for index, option in enumerate(quesiton.option):
# document.add_paragraph(('ABCD')[index] + str(option))
# document.save(filename)
# for i in range(10):
# qss = createQuestion()
# createPaper('paper' + str(i + 1) + '.docx', '2023計算機考試', qss)
五 python操作PPT文件
# PPT操作
prs = pptx.Presentation('text.pptx') # 文件存在時可以寫明文件名稱
# 新增三張幻燈片
slide = prs.slides.add_slide(prs.slide_layouts[0])
# prs.slides.add_slide(prs.slide_layouts[1])
# prs.slides.add_slide(prs.slide_layouts[2])
# 刪除幻燈片
print(len(prs.slides)) # 幻燈片數(shù)量
# del prs.slides._sldIdLst[1] #刪除第二張幻燈片
# 設置幻燈片與上下左右的間距為5英寸
text1 = slide.shapes.add_textbox(Inches(5), Inches(5), Inches(5), Inches(5))
text1.text = '我是文本框'
p1 = text1.text_frame.add_paragraph()
p1.text = '我是段落1'
p1.add_run().text = 'end'
title_shape = slide.shapes.title
title_shape.text = '標題1'
slide.shapes.placeholders[1].text = '標題2'
# 添加圖形到PPT
shape = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, Inches(2), Inches(2), Inches(2), Inches(2)) # 矩形
# 填充、邊框
fill = shape.fill
fill.solid()
fill.fore_color.rgb = RGBColor(255, 0, 0)
line = shape.line
line.color.rbg = RGBColor(44, 22, 67)
line.width = Pt(2)
# 寫入表格: 2和3指2行3列,6指間隔左側(cè)與頂部的間隔,4指表格長寬
table = slide.shapes.add_table(3, 3, Inches(6), Inches(6), Inches(4), Inches(4)).table
# 向表格中插入內(nèi)容
table.cell(1, 0).text = 'name'
table.cell(1, 1).text = 'age'
table.cell(1, 2).text = 'class'
table.cell(2, 0).text = '小明'
table.cell(2, 1).text = '22'
table.cell(2, 2).text = '九年級一班'
# 合并單元格
cell = table.cell(0, 0)
cell1 = table.cell(0, 2)
cell.merge(cell1)
table.cell(0, 0).text = '班級信息'
# 取消合并
if cell.is_merge_origin: # 判斷當前單元格是否已經(jīng)被合并
cell.split()
# 寫入圖表
chart_data = CategoryChartData()
chart_data.categories = ['一月', '二月', '三月'] # X軸
chart_data.add_series('2022', (200, 500, 400))
chart_data.add_series('2020', (300, 800, 600))
chart = slide.shapes.add_chart(XL_CHART_TYPE.COLUMN_CLUSTERED, Inches(2), Inches(2), Inches(6), Inches(4),
chart_data).chart
chart.has_title = True
chart.chart_title.text_frame.text = '第一季度生產(chǎn)額'
chart.has_legend = True
chart.legend.position = XL_LEGEND_POSITION.RIGHT
prs.save('text.pptx') # 保存修改
到了這里,關于python實現(xiàn)辦公自動化的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!