当前位置:   article > 正文

python自动化高效办公第二期,带你项目实战【一】{excel数据处理、批量化生成word模板、pdf和ppt等自动化操作}_批量生成指定模板pdf

批量生成指定模板pdf

 相关文章和数据源:

Python自动化办公--Pandas玩转Excel【一】

Python自动化办公--Pandas玩转Excel数据分析【二】

Python自动化办公--Pandas玩转Excel数据分析【三】


python处理Excel实现自动化办公教学(含实战)【一】

python处理Excel实现自动化办公教学(含实战)【二】

python处理Excel实现自动化办公教学(数据筛选、公式操作、单元格拆分合并、冻结窗口、图表绘制等)【三】


python入门之后须掌握的知识点(模块化编程、时间模块)【一】

python入门之后须掌握的知识点(excel文件处理+邮件发送+实战:批量化发工资条)【二】


spandas玩转excel码源.zip-数据挖掘文档类资源-CSDN下载https://download.csdn.net/download/sinat_39620217/85202114

Python自动化办公(2021最新版!有源代码,).zip-Python自动化办公(2021最新版!有源代码,适合小白~).zip更多下载资源、学习资料请访问CSDN下载频道.https://download.csdn.net/download/sinat_39620217/85213092

Python自动化办公(可能是B站内容最全的!有源代码,).zip-Python自动化办公(可能是B站内容最全的!有源代码,).zip更多下载资源、学习资料请访问CSDN下载频道.https://download.csdn.net/download/sinat_39620217/85213100

上面是对应码源,图方便的话可以直接下载都分类分好了,当然也可以看文章。


1.知识巩固excel

这个系列文章主要以实例为主,学会每个demo,活学活用,办公效率提升飞快!

1.1 xlrd+xlwt读写excel

  1. #安装命令:
  2. pip install xlrd
  3. pip install xlwt

我们在读取文件的时候,excel的列是字母我们不容易直观看出来是第几列,下面对excel进行设置。

 操作如下

  1. import xlrd
  2. # 打开excel
  3. xlsx = xlrd.open_workbook('7月新.xls')
  4. sheet = xlsx.sheet_by_index(0)
  5. data = sheet.cell_value(5, 1)
  6. print(data)
  7. # for i in xlsx.sheet_names():
  8. # print(i)
  9. # table = xlsx.sheet_by_name(i)
  10. # print(table.cell_value(3, 3))
  11. # 通过sheet名查找:xlsx.sheet_by_name("7月下旬入库表")
  12. # 通过索引查找:xlsx.sheet_by_index(3)
  13. # print(table.cell_value(0, 0))
  14. #单元格读取方式
  15. print(sheet.cell_value(1, 2))
  16. print(sheet.cell(0, 0).value)
  17. print(sheet.row(0)[0].value)
  18. # for i in range(0, xlsx.nsheets):
  19. # sheet = xlsx.sheet_by_index(i)
  20. # print(sheet.name)
  21. # print(sheet.cell_value(0, 0))
  22. #
  23. # # 获取所有sheet名字:xlsx.sheet_names()
  24. # # 获取sheet数量:xlsx.nsheets
  25. #
  26. # for i in xlsx.sheet_names():
  27. # print(i)
  28. # table = xlsx.sheet_by_name(i)
  29. # print(table.cell_value(3, 3))
  1. import xlwt
  2. # 新建工作簿
  3. new_workbook = xlwt.Workbook()
  4. # 新建sheet
  5. worksheet = new_workbook.add_sheet('new_test')
  6. # 新建单元格,并写入内容-行列
  7. worksheet.write(1, 2, 'test')
  8. # 保存
  9. new_workbook.save('test.xls')

 

 1.2  xlutils设置格式

xlutils整体没有pandas设置来的方便

  1. from xlutils.copy import copy
  2. import xlrd
  3. import xlwt
  4. # 安装:pip install xlutils
  5. tem_excel = xlrd.open_workbook('日统计.xls', formatting_info=True) #格式信息打开
  6. tem_sheet = tem_excel.sheet_by_index(0)
  7. new_excel = copy(tem_excel)
  8. new_sheet = new_excel.get_sheet(0)
  9. style = xlwt.XFStyle()
  10. # 字体
  11. font = xlwt.Font()
  12. font.name = '微软雅黑'
  13. font.bold = True
  14. # 18*20
  15. font.height = 360
  16. style.font = font
  17. # 边框:细线==THIN
  18. borders = xlwt.Borders()
  19. borders.top = xlwt.Borders.THIN
  20. borders.bottom = xlwt.Borders.THIN
  21. borders.left = xlwt.Borders.THIN
  22. borders.right = xlwt.Borders.THIN
  23. style.borders = borders
  24. # 对齐
  25. alignment = xlwt.Alignment()
  26. alignment.horz = xlwt.Alignment.HORZ_CENTER
  27. alignment.vert = xlwt.Alignment.VERT_CENTER
  28. style.alignment = alignment
  29. new_sheet.write(2, 1, 12)
  30. new_sheet.write(3, 1, 18)
  31. new_sheet.write(4, 1, 19)
  32. new_sheet.write(5, 1, 15)
  33. # new_sheet.write(2, 1, 12, style)
  34. # new_sheet.write(3, 1, 18, style)
  35. # new_sheet.write(4, 1, 19, style)
  36. # new_sheet.write(5, 1, 15, style)
  37. new_excel.save('填写.xls')

 

 1.3 自动生成统计报表【案例一:分数统计】

  1. import xlrd
  2. import xlwt
  3. # 读取excel文件
  4. xlsx = xlrd.open_workbook('三年二班(各科成绩单).xls')
  5. # 选择指定sheet
  6. sheet = xlsx.sheet_by_index(0)
  7. all_data = []
  8. # 统计共有多少学生,并去重
  9. num_set = set()
  10. for row_i in range(1, sheet.nrows):
  11. num = sheet.cell_value(row_i, 0)
  12. name = sheet.cell_value(row_i, 1)
  13. grade = sheet.cell_value(row_i, 3)
  14. student = {
  15. 'num': num,
  16. 'name': name,
  17. 'grade': grade,
  18. }
  19. all_data.append(student)
  20. num_set.add(num)
  21. # print(all_data)
  22. # print(len(all_data))
  23. # print(len(num_set))
  24. # 计算总分
  25. sum_list = []
  26. for num in num_set:
  27. name = ''
  28. sum = 0
  29. for student in all_data:
  30. # print(student['num'])
  31. # print(num)
  32. if num == student['num']:
  33. sum += student['grade']
  34. name = student['name']
  35. sum_stu = {
  36. 'num': num,
  37. 'name': name,
  38. 'sum': sum
  39. }
  40. sum_list.append(sum_stu)
  41. print(sum_list)
  42. # 写入新的excel
  43. # 新建工作簿
  44. new_workbook = xlwt.Workbook()
  45. # 新建sheet
  46. worksheet = new_workbook.add_sheet('2班')
  47. # 新建单元格,并写入内容
  48. # 写入第一列的内容
  49. worksheet.write(0, 0, '学号')
  50. worksheet.write(0, 1, '姓名')
  51. worksheet.write(0, 2, '总分')
  52. # 自动写入后面的内容
  53. for row in range(0,len(sum_list)):
  54. worksheet.write(row+1,0,sum_list[row]['num'])
  55. worksheet.write(row+1,1,sum_list[row]['name'])
  56. worksheet.write(row+1,2,sum_list[row]['sum'])
  57. # 保存
  58. new_workbook.save('2班学生总分.xls')

 1.4 xlsxwriter 和openpyxl

xlwt会遇到不支持超过列256的表格

  1. # import xlwt
  2. #
  3. # workbook = xlwt.Workbook()
  4. # sheet0 = workbook.add_sheet('sheet0')
  5. # for i in range(0,300):
  6. # sheet0.write(0,i,i)
  7. # workbook.save('num.xls')
  8. # 不带格式
  9. import xlsxwriter as xw
  10. workbook = xw.Workbook('number.xlsx')
  11. sheet0 = workbook.add_worksheet('sheet0')
  12. for i in range(0,300):
  13. sheet0.write(0,i,i)
  14. workbook.close()
  15. # 性能不稳定
  16. import openpyxl
  17. workbook = openpyxl.load_workbook('number.xlsx')
  18. sheet0 = workbook['sheet0']
  19. sheet0['B3']= '2'
  20. sheet0['C2']= '4'
  21. sheet0['D7']= '3'
  22. workbook.save('num_open.xlsx')

1.5 xlwings和pandas

pandas在第一期已经详细讲解过,参考相关文章

Python用来处理Excel的全部可用库,以及它们的优缺点

xlwings具有以下优点:

- xlwings能够非常方便的读写Excel文件中的数据,并且能够进行单元格格式的修改
- 可以和matplotlib以及pandas无缝连接
- 可以调用Excel文件中VBA写好的程序,也可以让VBA调用用Python写的程序。
- 开源免费,一直在更新

  1. #### 1、打开/新建Excel文档
  2. ```python
  3. import xlwings as xw
  4. wb = xw.Book() # 新建一个文档
  5. wb = xw.Book('test.xlsx') # 打开一个已有的文档
  6. ```
  7. #### 2、读取/写入数据
  8. ```python
  9. sht = wb.sheets['Sheet1'] # 找到指定sheet
  10. print(sht.range('A1').value) # 读取指定单元格的数据,这里读的是A1
  11. sht.range('B1').value = 10 # 给指定的空白单元格赋值,这里赋值的是B1
  12. ```
  13. #### 3、保存文件、退出程序
  14. ```python
  15. wb.save(r'test.xlsx') #保存Excel文档,命名为test.xlsx,并保存在D盘
  16. wb.close() # 退出程序,该步骤不可省略
  17. ```
  18. #### 4、连接pandas处理复杂数据
  19. ```python
  20. import pandas as pd
  21. df = pd.DataFrame([[1,2], [3,4]], columns=['a', 'b'])
  22. sht.range('A1').value = df
  23. sht.range('A1').options(pd.DataFrame, expand='table').value
  24. ```
  25. #### 5、连接**Matplotlib** 画图
  26. ```python
  27. import matplotlib.pyplot as plt
  28. fig = plt.figure()
  29. plt.plot([1, 2, 3, 4, 5])
  30. sht.pictures.add(fig, name='MyPlot', update=True)

1.6 案例实战---把文件名整理到excel中

  1. import os
  2. import xlwt
  3. # 目标文件夹
  4. file_path = 'd:/'
  5. # 取出目标文件夹下的文件名
  6. os.listdir(file_path)
  7. new_workbook = xlwt.Workbook()
  8. sheet = new_workbook.add_sheet('new_dir')
  9. n = 0
  10. for i in os.listdir(file_path):
  11. sheet.write(n,0,i)
  12. n+=1
  13. new_workbook.save('dir.xls')

1.7  案例实战---excel填充画

把一幅画导入到excel中用每个单元格背景色生成原画

  1. # coding: utf-8
  2. from PIL import Image
  3. from xlsxwriter.workbook import Workbook
  4. class ExcelPicture(object):
  5. FORMAT_CONSTRAINT = 65536
  6. def __init__(self, pic_file, ratio=0.5):
  7. self.__pic_file = pic_file
  8. self.__ratio = ratio
  9. self.__zoomed_out = False
  10. self.__formats = dict()
  11. # 缩小图片
  12. def zoom_out(self, _img):
  13. _size = _img.size
  14. _img.thumbnail((int(_img.size[0] * self.__ratio), int(_img.size[1] * self.__ratio)))
  15. self.__zoomed_out = True
  16. # 对颜色进行圆整
  17. def round_rgb(self, rgb, model):
  18. return tuple([int(round(x / model) * model) for x in rgb])
  19. # 查找颜色样式,去重
  20. def get_format(self, color):
  21. _format = self.__formats.get(color, None)
  22. if _format is None:
  23. _format = self.__wb.add_format({'bg_color': color})
  24. self.__formats[color] = _format
  25. return _format
  26. # 操作流程
  27. def process(self, output_file='_pic.xlsx', color_rounding=False, color_rounding_model=5.0):
  28. # 创建xlsx文件,并调整行列属性
  29. self.__wb = Workbook(output_file)
  30. self.__sht = self.__wb.add_worksheet()
  31. self.__sht.set_default_row(height=9)
  32. self.__sht.set_column(0, 5000, width=1)
  33. # 打开需要进行转换的图片
  34. _img = Image.open(self.__pic_file)
  35. print('Picture filename:', self.__pic_file)
  36. # 判断是否需要缩小图片尺寸
  37. if self.__ratio < 1:
  38. self.zoom_out(_img)
  39. # 遍历每一个像素点,并填充对应的颜色到对应的Excel单元格
  40. _size = _img.size
  41. print('Picture size:', _size)
  42. for (x, y) in [(x, y) for x in range(_size[0]) for y in range(_size[1])]:
  43. _clr = _img.getpixel((x, y))
  44. # 如果颜色种类过多,则需要将颜色圆整到近似的颜色上,以减少颜色种类
  45. if color_rounding: _clr = self.round_rgb(_clr, color_rounding_model)
  46. _color = '#%02X%02X%02X' % _clr
  47. self.__sht.write(y, x, '', self.get_format(_color))
  48. self.__wb.close()
  49. # 检查颜色样式种类是否超出限制,Excel2007对样式数量有最大限制
  50. format_size = len(self.__formats.keys())
  51. if format_size >= ExcelPicture.FORMAT_CONSTRAINT:
  52. print('Failed! Color size overflow: %s.' % format_size)
  53. else:
  54. print('Success!')
  55. print('Color: %s' % format_size)
  56. print('Color_rounding:', color_rounding)
  57. if color_rounding:
  58. print('Color_rounding_model:', color_rounding_model)
  59. if __name__ == '__main__':
  60. r = ExcelPicture('test.jpg', ratio=0.5)
  61. r.process('0407.xlsx', color_rounding=True, color_rounding_model=5.0)
  62. # 同级目录

效果如下:

原图

下面可以看到有一点糊是因为填充单元格可以当作像素点来考虑

 

 2.自动化处理word

安装库

>pip install python-docx

- python-docx
    - 说明文档:https://python-docx.readthedocs.io/en/latest/#api-documentation

2.1 自动生成word【批量化写模板文档】

  1. from docx import Document
  2. from docx.enum.text import WD_ALIGN_PARAGRAPH
  3. from docx.shared import Pt
  4. from docx.oxml.ns import qn
  5. import time
  6. price = input('请输入工资调整金额:')
  7. # 全体员工姓名
  8. company_list = ['员工1', '员工1', '员工2', '员工3', '员工4',
  9. '员工5', '员工6', '员工7', '员工8', '员工9', '员工10']
  10. # word和excel可以结合
  11. # excel学习:for
  12. # 当天的日期!
  13. today = time.strftime("%Y{y}%m{m}%d{d}", time.localtime()
  14. ).format(y='年', m='月', d='日')
  15. for i in company_list:
  16. document = Document()
  17. # 设置文档的基础字体
  18. document.styles['Normal'].font.name = u'宋体'
  19. # 识别中文
  20. document.styles['Normal'].element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
  21. # 建立一个自然段
  22. p1 = document.add_paragraph()
  23. # 对齐方式为居中,没有这句的话默认左对齐
  24. p1.alignment = WD_ALIGN_PARAGRAPH.CENTER
  25. run1 = p1.add_run('关于%s工资调整的通知' % (today))
  26. run1.font.name = '微软雅黑'
  27. run1.element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑')
  28. run1.font.size = Pt(21)
  29. run1.font.bold = True
  30. p1.space_after = Pt(5)
  31. p1.space_before = Pt(5)
  32. p2 = document.add_paragraph()
  33. run2 = p2.add_run(i + ':')
  34. run2.font.name = '宋体'
  35. run2.element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
  36. run2.font.size = Pt(16)
  37. run2.font.bold = True
  38. p3 = document.add_paragraph()
  39. run3 = p3.add_run('因为疫情影响,我们很抱歉的通知您,您的工资调整为每月%s元,特此通知' % price)
  40. run3.font.name = '宋体'
  41. run3.element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
  42. run3.font.size = Pt(14)
  43. p4 = document.add_paragraph()
  44. p4.alignment = WD_ALIGN_PARAGRAPH.RIGHT
  45. run4 = p4.add_run('人事:王小姐 电话:686868')
  46. run4.font.name = '宋体'
  47. run4.element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
  48. run4.font.size = Pt(14)
  49. run4.font.bold = True
  50. document.save('%s-工资调整通知.docx' % i)

其中在读取员工信息这块可以和excel结合。

 

2.2 批量化写模板文档【并添加图片和表格】

新的要求,要求小杨在通知函上方加上图片红头,价格数据以表格形式展示。并在第二页加
上广告【插入分页符】。

效果如下:

  1. from docx import Document
  2. from docx.enum.text import WD_ALIGN_PARAGRAPH
  3. from docx.shared import Pt
  4. from docx.oxml.ns import qn
  5. from docx.shared import Inches
  6. import time
  7. price = input('请输入工资调整金额:')
  8. company_list = ['员工1', '员工1', '员工2', '员工3', '员工4',
  9. '员工5', '员工6', '员工7', '员工8', '员工9', '员工10', ]
  10. today = time.strftime("%Y{y}%m{m}%d{d}", time.localtime()
  11. ).format(y='年', m='月', d='日')
  12. for i in company_list:
  13. document = Document()
  14. # 设置文档的基础字体
  15. document.styles['Normal'].font.name = u'宋体'
  16. document.styles['Normal'].element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
  17. # 红头文件加入文件
  18. document.add_picture('title002.jpg', width=Inches(6))
  19. # 建立一个自然段
  20. p1 = document.add_paragraph()
  21. # 对齐方式为居中,没有这句的话默认左对齐
  22. p1.alignment = WD_ALIGN_PARAGRAPH.CENTER
  23. run1 = p1.add_run('关于%s工资调整的通知' % (today))
  24. run1.font.name = '微软雅黑'
  25. run1.element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑')
  26. run1.font.size = Pt(21)
  27. run1.font.bold = True
  28. p1.space_after = Pt(5)
  29. p1.space_before = Pt(5)
  30. p2 = document.add_paragraph()
  31. run2 = p2.add_run(i + ':')
  32. run2.font.name = '宋体'
  33. run2.element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
  34. run2.font.size = Pt(16)
  35. run2.font.bold = True
  36. p3 = document.add_paragraph()
  37. run3 = p3.add_run('因为疫情影响,我们很抱歉的通知您,您的工资调整为每月%s元,特此通知。' % price)
  38. run3.font.name = '宋体'
  39. run3.element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
  40. run3.font.size = Pt(14)
  41. #添加表格
  42. table = document.add_table(rows=2, cols=2, style='Table Grid')#默认格式
  43. # 合并单元格
  44. table.cell(0, 0).merge(table.cell(0, 1)) #坐上合并到右下
  45. table_run1 = table.cell(0, 0).paragraphs[0].add_run('签名栏')
  46. table_run1.font.name = '黑体'
  47. table_run1.element.rPr.rFonts.set(qn('w:eastAsia'), u'黑体')
  48. table.cell(0, 0).paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
  49. table.cell(1, 0).text = i
  50. table.cell(1, 0).paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
  51. p4 = document.add_paragraph()
  52. p4.alignment = WD_ALIGN_PARAGRAPH.RIGHT
  53. run4 = p4.add_run('人事:王小姐 电话:686868')
  54. run4.font.name = '宋体'
  55. run4.element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
  56. run4.font.size = Pt(14)
  57. run4.font.bold = True
  58. #插入分页符
  59. document.add_page_break()
  60. p5= document.add_paragraph()
  61. run4=p5.add_run("此处是广告")
  62. document.save('%s-工资调整通知.docx' % i)

2.3 读取word文档【 文字+表格混合文档:

  1. from docx import Document
  2. document = Document('pure.docx')
  3. all_paragraphs = document.paragraphs
  4. for p in all_paragraphs:
  5. print(p.text)
  6. # excel写入

 如果word里是表格呈现读取如下:

 文字+表格形式:

word基本格式问题:把word重名后缀为zip的文件,打开看到里面有xml的格式文件

 导入zipfile库解压文件,设置格式只读取我们需要的文字:进行组合。

  1. import zipfile
  2. word_book = zipfile.ZipFile('word_table.docx')
  3. xml = word_book.read("word/document.xml").decode('utf-8')
  4. # print(xml)
  5. xml_list = xml.split('<w:t>')
  6. # print(xml_list)
  7. text_list = []
  8. for i in xml_list:
  9. if i.find('</w:t>') + 1:
  10. text_list.append(i[:i.find('</w:t>')])
  11. else:
  12. pass
  13. text = "".join(text_list)
  14. print(text)

2.4 word转pdf(批量化)

安装库:

pip install pywin32
  1. from win32com.client import Dispatch,constants,gencache
  2. doc_path = 'test.docx'
  3. pdf_path = 'test.pdf'
  4. gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}',0,8,4)
  5. wd = Dispatch("Word.Application")
  6. doc = wd.Documents.Open(doc_path,ReadOnly=1)
  7. doc.ExportAsFixedFormat(pdf_path,constants.wdExportFormatPDF,
  8. Item=constants.wdExportDocumentWithMarkup,
  9. CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
  10. wd.Quit(constants.wdDoNotSaveChanges)

在执行时报错了,下面来说解决方法。
参考网站:

win32api pywin32 安装后出现 ImportError: DLL load failed_mengfanteng的博客-CSDN博客

  • 找到我们安装python的文件夹,在Lib文件中找到site-packages\pywin32_system32
  • D:\Program Files (x86)\Python\Python36\Lib\site-packages\pywin32_system32
  • 把里面的所有的文件复制到:C:\Windows\System32
  1. import os
  2. from win32com.client import Dispatch,constants,gencache
  3. from docx import Document
  4. from docx.enum.text import WD_ALIGN_PARAGRAPH
  5. from docx.shared import Pt
  6. from docx.oxml.ns import qn
  7. import time
  8. price = input('请输入工资调整金额:')
  9. # 全体员工姓名
  10. company_list = ['员工1', '员工1', '员工2', '员工3', '员工4', '员工5', '员工6', '员工7', '员工8', '员工9', '员工10' ]
  11. # 当天的日期
  12. today = time.strftime("%Y{y}%m{m}%d{d}", time.localtime()).format(y='年', m='月', d='日')
  13. for i in company_list:
  14. document = Document()
  15. # 设置文档的基础字体
  16. document.styles['Normal'].font.name = u'宋体'
  17. # 识别中文
  18. document.styles['Normal'].element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
  19. # 建立一个自然段
  20. p1 = document.add_paragraph()
  21. # 对齐方式为居中,没有这句的话默认左对齐
  22. p1.alignment = WD_ALIGN_PARAGRAPH.CENTER
  23. run1 = p1.add_run('关于%s工资调整的通知' % (today))
  24. run1.font.name = '微软雅黑'
  25. run1.element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑')
  26. run1.font.size = Pt(21)
  27. run1.font.bold = True
  28. p1.space_after = Pt(5)
  29. p1.space_before = Pt(5)
  30. p2 = document.add_paragraph()
  31. run2 = p2.add_run(i + ':')
  32. run2.font.name = '宋体'
  33. run2.element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
  34. run2.font.size = Pt(16)
  35. run2.font.bold = True
  36. p3 = document.add_paragraph()
  37. run3 = p3.add_run('因为疫情影响,我们很抱歉的通知您,您的工资调整为每月%s元,特此通知' % price)
  38. run3.font.name = '宋体'
  39. run3.element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
  40. run3.font.size = Pt(14)
  41. p4 = document.add_paragraph()
  42. p4.alignment = WD_ALIGN_PARAGRAPH.RIGHT
  43. run4 = p4.add_run('人事:王小姐 电话:686868')
  44. run4.font.name = '宋体'
  45. run4.element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
  46. run4.font.size = Pt(14)
  47. run4.font.bold = True
  48. document.save('%s-工资调整通知.docx' % i)
  49. doc_path = '%s-工资调整通知.docx' % i
  50. pdf_path = '%s-工资调整通知.pdf' % i
  51. gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}',0,8,4)
  52. wd = Dispatch("Word.Application")
  53. doc = wd.Documents.Open(doc_path,ReadOnly=1)
  54. doc.ExportAsFixedFormat(pdf_path,constants.wdExportFormatPDF,Item=constants.wdExportDocumentWithMarkup,CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
  55. wd.Quit(constants.wdDoNotSaveChanges)
  56. time.sleep(10)

3.PDF识别以及读取PDF中文字【pdf合并】

3.1 使用 pdfplumber和PyPDF2

安装库:

  1. pip install pdfplumber
  2. pip install PyPDF2

参考文章:

PDFPlumber使用入门_顺其自然~的博客-CSDN博客_pdfplumber

  1. import PyPDF2
  2. import pdfplumber
  3. def extract_content(pdf_path):
  4. # 内容提取,使用 pdfplumber 打开 PDF,用于提取文本
  5. with pdfplumber.open(pdf_path) as pdf_file:
  6. # 使用 PyPDF2 打开 PDF 用于提取图片
  7. pdf_image_reader = PyPDF2.PdfFileReader(open(pdf_path, "rb"))
  8. print(pdf_image_reader.getNumPages())
  9. content = ''
  10. # len(pdf.pages)为PDF文档页数,一页页解析
  11. for i in range(len(pdf_file.pages)):
  12. print("当前第 %s 页" % i)
  13. # pdf.pages[i] 是读取PDF文档第i+1页
  14. page_text = pdf_file.pages[i]
  15. # page.extract_text()函数即读取文本内容
  16. page_content = page_text.extract_text()
  17. if page_content:
  18. content = content + page_content + "\n"
  19. print(page_content)
  20. extract_content('静夜思.pdf')

合并pdf

  1. from PyPDF2 import PdfFileReader, PdfFileWriter
  2. def merge_pdfs(paths, output):
  3. pdf_writer = PdfFileWriter()
  4. for path in paths:
  5. pdf_reader = PdfFileReader(path)
  6. for page in range(pdf_reader.getNumPages()):
  7. # 把每张PDF页面加入到这个可读取对象中
  8. pdf_writer.addPage(pdf_reader.getPage(page))
  9. # 把这个已合并了的PDF文档存储起来
  10. with open(output, 'wb') as out:
  11. pdf_writer.write(out)
  12. if __name__ == '__main__':
  13. paths = ['静夜思.pdf', '静夜思.pdf']
  14. merge_pdfs(paths, output='pandas官方文档中文版.pdf')
  1. from PyPDF2 import PdfFileReader, PdfFileWriter
  2. def merge_pdfs(paths, output):
  3. pdf_writer = PdfFileWriter()
  4. for path in paths:
  5. pdf_reader = PdfFileReader(path)
  6. for page in range(pdf_reader.getNumPages()):
  7. # 把每张PDF页面加入到这个可读取对象中
  8. pdf_writer.addPage(pdf_reader.getPage(page))
  9. # 把这个已合并了的PDF文档存储起来
  10. with open(output, 'wb') as out:
  11. pdf_writer.write(out)
  12. if __name__ == '__main__':
  13. paths = ['study.pdf', 'labuladong的算法小抄官方完整版.pdf']
  14. merge_pdfs(paths, output='pandas官方文档中文版.pdf')

3.2 pdfminer(推荐)

读取:

 4.ppt自动化操作

 python-pptx说明文档
    - https://pypi.org/project/python-pptx/

# pip install python-pptx

4..1在ppt中写入文字

  1. from pptx import Presentation
  2. from pptx.util import Inches,Pt
  3. ppt = Presentation()
  4. slide = ppt.slides.add_slide(ppt.slide_layouts[1])# 在PPT中插入一个幻灯片
  5. body_shape = slide.shapes.placeholders
  6. # body_shape[0].text = '这是占位符0'
  7. # body_shape[1].text = '这是占位符1'
  8. #
  9. title_shape = slide.shapes.title
  10. title_shape.text = '这是标题'
  11. # subtitle = slide.shapes.placeholders[1] #取出本页第二个文本框
  12. # subtitle.text = '这是文本框'
  13. #
  14. # new_paragraph = body_shape[1].text_frame.add_paragraph()
  15. # new_paragraph.text = '新段落'
  16. # new_paragraph.font.bold = True
  17. # new_paragraph.font.italic = True
  18. # new_paragraph.font.size = Pt(15)
  19. # new_paragraph.font.underline = True
  20. #
  21. left = Inches(2)
  22. top = Inches(2)
  23. width = Inches(3)
  24. height = Inches(3)
  25. #
  26. #
  27. #
  28. textbox = slide.shapes.add_textbox(left,top,width,height)
  29. textbox.text = 'new textbox'
  30. # 如何在文本框里添加第二段文字?
  31. # new_para = textbox.text_frame.add_paragraph()
  32. # new_para.text = '第二段文字'
  33. #
  34. ppt.save('test.pptx')

4.2 在ppt插入图片表格

  1. # pip install python-pptx
  2. from pptx import Presentation
  3. from pptx.util import Inches,Pt
  4. ppt = Presentation()
  5. slide = ppt.slides.add_slide(ppt.slide_layouts[1])# 在PPT中插入一个幻灯片
  6. left = Inches(1)
  7. top = Inches(1)
  8. width = Inches(2)
  9. height = Inches(2)
  10. img = slide.shapes.add_picture('img.jpg',left,top,width,height)
  11. rows = 2
  12. cols = 2
  13. left = Inches(1)
  14. top = Inches(1)
  15. width = Inches(4)
  16. height = Inches(4)
  17. table = slide.shapes.add_table(rows,cols,left,top,width,height).table
  18. table.columns[0].width = Inches(1)
  19. table.columns[1].width = Inches(3)
  20. table.cell(0,0).text = '00'
  21. table.cell(0,1).text = '01'
  22. table.cell(1,0).text = '10'
  23. table.cell(1,1).text = '11' #二进制的11,代表十进制的多少?
  24. ppt.save('text.pptx')

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/623558
推荐阅读
相关标签
  

闽ICP备14008679号