前言

我是一个学什么都慢的人,往往所学的跟不上时代的热潮……而且写东西也慢。
老早前就要学点Python,但是时至今日还是毫无进展
2021-12-17T07:03:49.png

需求

  • 一朋友需要批量处理Word、Excel文件
  • Word文件中有个单元格问题本需要替换
  • Excel 文件中同样有个单元格文本需要替换
  • 每个目录下有 2 个docx文件需要修改
  • 每个目录下有 3 个 xlsx文件需要修改

思路

  • 第三方库

    • Word 用 Python-docx 库来处理
    • Excel 用 openpyxl 库来处理
  • Word 文件替换采用匹配替换,就是匹配到指定字符串,然后进行替换
  • Excel直接单元格赋值

问题

  • Word替换后,表格格式会变,而且字符串过长有换行导致页面发生变化
  • Excel 主要是字符串过长导致换行问题

代码实现

  • 库的安装

    • pip install python-docx
    • pip install openpyxl
  • 文件绝对路径获取代码

    def get_f(root_path,all_files=[]):
      files = os.listdir(root_path)
      for file in files:
          if not os.path.isdir(root_path + '/' + file):
              all_files.append(root_path + '/' + file)
          else:
              get_f((root_path + '/' + file),all_files)
      return all_files
  • docx 文件修改代码

    def update_word(doc,wrow,wline,new_info):
      tables = doc.tables
      table = tables[0]
      # 清空原有的文本
      table.cell(wrow,wline).paragraphs[0].runs[0].text = ''
      run= table.cell(wrow,wline).paragraphs[0].add_run(new_info)
      # 设置字体大小
      run.font.size = Pt(8)
  • xlsx 文件修改代码

    def update_excel(file,new_info):
      wb1 = openpyxl.load_workbook(file)
      worksheet = wb1.worksheets[0]
      fa = file.split('、')
      fb = fa[0].split('/')
      if fb[-1] == '1':
          worksheet["C3"] = new_info
      elif fb[-1] == '2':
          worksheet["D4"] = new_info
      else:
          worksheet["C4"] = new_info
      wb1.save(file)
      print(file+" 修改成功")

完整代码

# coding=utf-8

import os,docx,openpyxl
from docx.shared import Pt
from openpyxl.styles import Font
'''
Version 3.5
1. 此次主要修复docx表格修改后格式变的问题以及fontsize 改为 8
2. 此次采用更简洁的操作方式 --- 定位表格
3. 当前脚本适配 2 个Word文件,如果有增加请根据代码逻辑增加判断
4. 本脚本需要第三方库 python-docx,如未安装请自行安装 pip install docx
5. 此版本可以同时处理Excel文件,同样根据自己的实际情况做调整(Excel 匹配3个文件,且格式为 xlsx)
'''

# 工作目录
path = './test'
new_info = '修改后的字符'

# 获取文件绝对路径
def get_f(root_path,all_files=[]):
    files = os.listdir(root_path)
    for file in files:
        if not os.path.isdir(root_path + '/' + file):
            all_files.append(root_path + '/' + file)
        else:
            get_f((root_path + '/' + file),all_files)
    return all_files

# Excel 文件修改方法
def update_excel(file,new_info):
    wb1 = openpyxl.load_workbook(file)
    worksheet = wb1.worksheets[0]
    fa = file.split('、')
    fb = fa[0].split('/')
    if fb[-1] == '1':
        worksheet["C3"] = new_info
        worksheet["C3"].font = Font(size=8)
    elif fb[-1] == '2':
        worksheet["D4"] = new_info
        worksheet["D4"].font = Font(size=8)
    else:
        worksheet["C4"] = new_info
        worksheet["C4"].font = Font(size=8)
    wb1.save(file)
    print(file+" 修改成功")

# Word 文件修改方法
def update_word(doc,wrow,wline,new_info):
    tables = doc.tables
    table = tables[0]
    table.cell(wrow,wline).paragraphs[0].runs[0].text = ''
    run= table.cell(wrow,wline).paragraphs[0].add_run(new_info)
    run.font.size = Pt(8)

# 开始修改
for file in get_f(path):
    f = file.split(".")
    if f[2] == 'xlsx':
        update_excel(file,new_info)
    elif f[2] == 'docx':
        doc = docx.Document(file)
        fw0 = file.split("、")
        fw1 = fw0[0].split("/")
        if fw1[-1] == '1':
            wrow = 2
            wline = 1
        elif fw1[-1] == '2':
            wrow = 2
            wline = 3

        update_word(doc,wrow,wline,new_info)
        doc.save(file.format(file.split("/")[-1]))
        print(file+" 修改成功")

「 希望熬过一切,星光璀璨 」

流年小站,感谢有您的支持

「 道路坎坷,感谢有您 ---来自 anYun 的感谢 」

使用微信扫描二维码完成支付

2021-12-17
已阅:23710 人/次

 
 
 
分享是一种美德 x
打开微信,右上角的"+"选择"扫一扫"
使用“扫一扫”将博文分享至朋友圈吧

本文由 anYun 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。
我的博客即将同步至腾讯云开发者社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=3oibnoh9lo6cs

还不快抢沙发

添加新评论

Myssl安全认证