2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > Python办公自动化之二 操作word

Python办公自动化之二 操作word

时间:2021-10-04 16:47:17

相关推荐

Python办公自动化之二 操作word

1. python-docx模块

word的自动化针对手动创建批量制式Word文件、修改现有大量word文件存在的共性问题python-docx是第三方模块,用于自动化生成和修改word文档

from docx import Documentfrom docx.shared import Pt,RGBColorfrom docx.enum.style import WD_STYLE_TYPE# Word文档字体和Pt字体大小的对照表# 八号 5# 七号 5.5# 小六 6.5# 六号 7.5# 小五 9# 五号 10.5# 小四 12# 四号 14# 小三 15# 三号 16# 小二 18# 二号 22# 小一 24# 一号 26# 小初 36# 初号 42# 1. 创建一个文档对象document = Document() #新建文档对象# Document('已经存在的.docx')#读取已经存在的文档# 2. 写入内容document.add_heading('我爱你', level=2) # 标题,级别为h2# word文档的样式处理(可以统一样式)[内置样式或者自定义样式]style = document.styles.add_style('textstyle', WD_STYLE_TYPE.PARAGRAPH)# print(style.style_id)# print(style.name)style.font.size = Pt(5)#删除样式# document.styles['textstyle'].delete()# 段落p1 = document.add_paragraph('我爱你,像风走过了3000里! 如果某一天,你不喜欢我了,我希望先开口的人是我,而不是你。渣男不渣,只是他们的心碎成了很多片。',style='textstyle')p1.insert_paragraph_before("baby, i want to say you :")format = p1.paragraph_formatformat.left_indent = Pt(20) # 缩进format.right_indent = Pt(20) # 缩进# 首行缩进format.first_line_indent = Pt(20)#设置行间距format.line_spacing = 1.5#追加段落run = p1.add_run('耳旁软语是你,声嘶力竭也是你。爱的是你,离开的也是你。曾共度两三年的是你,而今老死不相往来也是你。')run.font.size = Pt(12)run.font.name = '微软雅黑'run.font.color.rgb=RGBColor(235,33,24)run1 = p1.add_run('只要最后是你就好。')run1.bold = Truerun1.font.underline = Truerun1.font.italic = True# 插入图片(指定宽高)document.add_picture('plant.png', Pt(20), Pt(30))# 插入表格table = document.add_table(rows=1, cols=3, style='Medium List 1') #表格样式这里我使用的是内置样式,可以查阅官方文档# 构建表格header_cells = table.rows[0].cellsheader_cells[0].text = '地区'header_cells[1].text = '最低彩礼'header_cells[2].text = '最高彩礼'# 为表格插入数据data =(["四川", 5, 15],["江西", 30, 50],["乐山", 0, 10],)for item in data:rows_cells = table.add_row().cells # 添加并构建表格rows_cells[0].text = str(item[0])rows_cells[1].text = str(item[1])rows_cells[2].text = str(item[2])# 获取word文档中的表格print(len(document.tables[0].rows)) # 打印总行数print(len(document.tables[0].columns)) # 打印总列数#cellprint(document.tables[0].cell(0,2).text)#获取表格第一行第3列的内容# 3. 保存文档document.save('test.docx')

2. docx2pdf模块

word转换为pdf

from docx2pdf import convertimport pdfkitimport oscurrentDir = os.getcwd()convert(input_path = currentDir + r"\test.docx", output_path = currentDir + r"\test.pdf")

第二种Word转换为pdf的方法

from win32com.client import constants, gencacheimport os# 单个文件的转换def createPdf(wordPath, pdfPath):word = gencache.EnsureDispatch("Word.Application") # 创建Word程序对象doc = word.Documents.Open(wordPath, ReadOnly=1) # 读取word文件# 转换方法doc.ExportAsFixedFormat(pdfPath, constants.wdExportFormatPDF) # 更多信息访问office开发人员中心文档word.Quit()# createPdf('E:\PycharmProjects\WorkAuto\yinlei.docx','E:\PycharmProjects\WorkAuto\yinlei.pdf' )# 多个文件的转换# 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'createPdf(filepath, pdfpath)

3. python-pptx模块

针对批量PPT的创建和修改i、大量图片、文字的写入、准确无误的插入图标等数据python-pptx是第三方模块、自动生成和更新PowerPoint(.pptx)文件

import pptxfrom pptx.util import Inches, Pt # 英寸from pptx.enum.shapes import MSO_SHAPEfrom pptx.dml.color import RGBColorfrom pptx.chart.data import CategoryChartDatafrom pptx.enum.chart import XL_CHART_TYPEfrom pptx.enum.chart import XL_LEGEND_POSITION# 步骤:# 1. 得到演示文稿的对像prs = pptx.Presentation()# 修改现有的ppt文件Presentation('xxx.pptx')# 2. 写入操作slide = prs.slides.add_slide(prs.slide_layouts[0]) #插入一张幻灯片 slide_layouts是微软ppt软件内置的ppt模板集合,通过索引访问具体使用哪个内置模板prs.slides.add_slide(prs.slide_layouts[1])prs.slides.add_slide(prs.slide_layouts[2])# 删除幻灯片print(len(prs.slides))del prs.slides._sldIdLst[1]print(len(prs.slides))# 给某个幻灯片操作text1 = slide.shapes.add_textbox(Inches(5),Inches(5),Inches(5),Inches(5))text1.text = 'i am yinlei'p1 = text1.text_frame.add_paragraph()p1.text = '我是段落1'p1.add_run().text = '结束'title_shape = slide.shapes.titletitle_shape.text = 'title one'slide.shapes.placeholders[1].text = 'title two'# 添加图形到ppt(自选图形)shape = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE,Inches(2),Inches(2),Inches(5),Inches(3))# 设置图形的填充和边框fill = shape.fillfill.solid()fill.fore_color.rgb=RGBColor(255,0,0)line = shape.lineline.color.rgb = RGBColor(55,3,5)line.width = Pt(2)# 添加表格table = slide.shapes.add_table(3,3,Inches(2),Inches(2),Inches(4),Inches(2)).tabletable.cell(1,0).text = 'name'table.cell(1,1).text = 'age'table.cell(1,2).text = 'class'table.cell(2,0).text = 'yinlei'table.cell(2,1).text = '21'table.cell(2,2).text = '1班'# 合并单元格cell = table.cell(0,0)cell1 = table.cell(0,2)cell.merge(cell1)table.cell(0,0).text='student info'#取消合并# print(cell.is_merge_origin) # 是否合并的# cell.split()# 插入图表chart_data = CategoryChartData()chart_data.categories = ['月份','一月份','二月份']chart_data.add_series('', (300,400,500))chart_data.add_series('', (500,300,200))chart = slide.shapes.add_chart(XL_CHART_TYPE.LINE, Inches(2),Inches(2),Inches(6),Inches(4),chart_data).chartchart.has_title = Truechart.chart_title.text_frame.text = '销售额'chart.has_legend = True # 显示图例chart.legend.position = XL_LEGEND_POSITION.RIGHT# 3. 保存ppt文件prs.save('yinlei.pptx')

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。