zoukankan      html  css  js  c++  java
  • 批量替换word内容

    有一个需求需要把word中的一段文档的编号批量替换

    如,把133-183批量的替换成31-81,需要批量的替换word,脚本如下

    from docx import Document
    import os
    
    oldFile = "C:\Users\wuzs\Desktop\test.docx"
    newFile = "C:\Users\wuzs\Desktop\test2.docx"
    
    DICT = {
    "SP_OS_NETWORK_133":"SP_OS_NETWORK_031",
    "SP_OS_NETWORK_134":"SP_OS_NETWORK_032",
    "SP_OS_NETWORK_135":"SP_OS_NETWORK_033",
    "SP_OS_NETWORK_136":"SP_OS_NETWORK_034",
    *****************
    
    *****************
    "SP_OS_NETWORK_182":"SP_OS_NETWORK_080",
    "SP_OS_NETWORK_183":"SP_OS_NETWORK_081",
    
    }
    
    
    def main():
        document = Document(oldFile)
        document = check(document)
        document.save(newFile)
    
    
    def check(document):
        # tables
        for table in document.tables:
            for row in range(len(table.rows)):
                for col in range(len(table.columns)):
                    for key, value in DICT.items():
                        if key in table.cell(row, col).text:
                            print(key + "->" + value)
                            table.cell(row, col).text = table.cell(row, col).text.replace(key, value)
    
        # paragraphs
        for para in document.paragraphs:
            for i in range(len(para.runs)):
                for key, value in DICT.items():
                    if key in para.runs[i].text:
                        print(key + "->" + value)
                        para.runs[i].text = para.runs[i].text.replace(key, value)
    
        return document
    
    
    if __name__ == '__main__':
        main()
    
    
  • 相关阅读:
    20150306+Linux安装+常用命令-01
    补充:javascript
    补充:数组循环与思路
    补充:控制语句
    DOM操作的概念
    什么是数组?
    补充:MySQL整理
    MySQL数据查询
    补充:MySQL经典45道题型
    表单 form:标签、类型、注意事项
  • 原文地址:https://www.cnblogs.com/mrwuzs/p/11444594.html
Copyright © 2011-2022 走看看