51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

手机号码,快捷登录

查看: 1068|回复: 0
打印 上一主题 下一主题

[python] 教您如何使用Python在Word中实现批量操作的神奇!

[复制链接]
  • TA的每日心情
    擦汗
    昨天 08:59
  • 签到天数: 1021 天

    连续签到: 2 天

    [LV.10]测试总司令

    跳转到指定楼层
    1#
    发表于 2022-8-26 15:48:32 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
    Python在平时写写小工具真是方便快捷,Pyhon大法好!
      以下所有代码都是找了好多网上的大佬分享的代码按照自己的需求改的。调用的库为Python-docx、win32com、PyPDF2、xlwings(操作excel)。
      因为公司的任务要对上千个word文件进行批量操作,手工操作太累了,于是加班加点赶出来了一个自动化脚本,虽然还有很多要优化的地方,但已经可以稳定运行了。
      下面记录一下脚本功能。
      doc转docx
      因为Python-docx库只能对docx文件操作,所以要转格式,直接改后缀不行。
    1. word = wc.Dispatch("Word.Application")
    2.     # 不能用相对路径,老老实实用绝对路径
    3.     # 需要处理的文件所在文件夹目录
    4.     for root, dirs, files in os.walk(rawpath):
    5.         for i in files:
    6.             # 找出文件中以.doc结尾并且不以~$开头的文件(~$是为了排除临时文件的)
    7.             if i.endswith('.doc') and not i.startswith('~
    8. [font=&quot][size=16px][b]找到特定文件[/b][/size][/font]
    9. [font=&quot][size=16px]  这个比较简单,只需要循环遍历文件夹,按照队列里的关键字将目标文件添加到队列里即可。[/size][/font]
    10. [font=&quot][size=16px]  因为转pdf只能是docx,所以要找docx文件,同时过滤~$文件开头的临时文件。[/size][/font]
    11. [font=&quot][size=16px][code]def findfiles():
    12.     count = 1
    13.     for root, dirs, files in os.walk(path):
    14.         for filename in files:
    15.             for i in range(len(filenames)):
    16.                 if (filenames[i] in filename and filename.endswith('docx') and not filename.startswith('~[b]所有字体颜色变为黑色[/b][/size][/font]
    17. [font=&quot][size=16px][indent]def change_color(path):

    18.     file = Document(path)
    19.     for pag in file.paragraphs:
    20.         for block in pag.runs:
    21.             block.font.color.rgb = RGBColor(0, 0, 0)
    22.     for table in file.tables:
    23.         for row in table.rows:
    24.             for cell in row.cells:
    25.                 for cell_pag in cell.paragraphs:
    26.                     for cell_block in cell_pag.runs:
    27.                         cell_block.font.color.rgb = RGBColor(0, 0, 0)

    28.     # 页眉
    29.     pag_head = file.sections[0].header
    30.     head_pag = pag_head.paragraphs[0]
    31.     for run in head_pag.runs:
    32.         run.font.color.rgb = RGBColor(0, 0, 0)

    33.     #  页脚
    34.     pag_foot = file.sections[0].footer
    35.     foot_pag = pag_foot.paragraphs[0]
    36.     for run in foot_pag.runs:
    37.         run.font.color.rgb = RGBColor(0, 0, 0)
    38.     file.save(path)
    39.     print(path)
    40.     print("^"*10 + "颜色切换完成" + "^"*10)[/indent]
    41. [b]docx转pdf[/b]
    42.   因为分页操作只能pdf实现。
    43. [code]for i in range(len(result)):
    44.     file = result[i][1]
    45.     name = file.rsplit('\\', 1)[1]
    46.     print(i)
    47.     if "关键字" in name:  # 跳过不需要截取的关键字文件
    48.         outfile = pdf_file_path + name[:-5] + str(i) +'.pdf'
    49.     else:
    50.         outfile = out_path + name[:-5] + str(i) +'.pdf'  

    51.     if file.split(".")[-1] == 'docx':
    52.         print(file)
    53.         convert(file, outfile)
    54.     print("^"*10+"PDF转换完成"+"^"*10)
    55.     time.sleep(1)
    复制代码
    截取特定页面
    1. def split_single_pdf(read_file, start_page, end_page, pdf_file):
    2.     # 1. 获取原始pdf文件
    3.     fp_read_file = open(read_file, 'rb')
    4.     # 2. 将要分割的PDF内容格式化
    5.     pdf_input = PdfFileReader(fp_read_file)
    6.     # 3. 实例一个 PDF文件编写器
    7.     pdf_output = PdfFileWriter()
    8.     # 4. 把第一页放到PDF文件编写器
    9.     for i in range(start_page, end_page):
    10.         pdf_output.addPage(pdf_input.getPage(i))
    11.     # 5. PDF文件输出
    12.     with open(pdf_file, 'wb') as pdf_out:
    13.         pdf_output.write(pdf_out)
    14.     print(f'{read_file}分割{start_page}页-{end_page}页完成,保存为{pdf_file}!')
    复制代码
    调用打印机打印
    1. def printer_loading(filename):
    2.     win32api.ShellExecute(0, "print", filename, '/d:"%s"' % win32print.GetDefaultPrinter(), ".", 0)
    复制代码

    对execl特定页面打印
    1. def excel_print(execl_path):
    2.     app = xw.App(visible=False, add_book=False)
    3.     workbook = app.books.open(execl_path)
    4.     worksheet = workbook.sheets['sheet关键字']
    5.     area = worksheet.range('A1:D11')  # 打印区域
    6.     area.api.PrintOut(Copies=1, ActivePrinter='Canon MF260 Series UFRII LT', Collate=True)
    7.     workbook.close()
    8.     app.quit()
    9. ):
    10.                 print(i)
    11.                 doc = word.Documents.Open(root +'\\'+ i)
    12.                 # # 将文件名与后缀分割
    13.                 rename = os.path.splitext(i)
    14.                 # 将文件另存为.docx
    15.                 doc.SaveAs(root + '\\' +rename[0] + '.docx', 12)  # 12表示docx格式
    16.                 doc.Close()
    17.                 # time.sleep(1)
    18.     word.Quit()
    复制代码



    分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    本版积分规则

    关闭

    站长推荐上一条 /1 下一条

    小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

    GMT+8, 2024-9-20 11:10 , Processed in 0.078471 second(s), 23 queries .

    Powered by Discuz! X3.2

    © 2001-2024 Comsenz Inc.

    快速回复 返回顶部 返回列表