python 操作 doc /docx

发布时间:2019-08-09 10:19:56编辑:auto阅读(1559)

    对于python来说操作 doc    需要用到

    win32com      安装   pip  install  win32com      

    优点 doc所有的操作都可以执行     缺点 如果没有office就死翘翘了 当然也可以com  wsp    对于这种需要强制安装xx的不是很喜欢 重点介绍   另一款  python   docx的包 


    先安装指令   

        pip install python_docx  注意不是  pip install docx    我就是一开始安装的  pip install docx  让我怀疑人生以为包没加载进去 折腾俩个多小时。才发现指令错了

     官方网址 https://python-docx.readthedocs.io/en/latest/user/quickstart.html#opening-a-document



    写的比较详细     我重点说一下我开发过程需要做到对一个docx文件模板进行内容的替换 和修改  

    先加载一个 有的docx文件

    from docx import Document

    document = Document(r"*\公告模板.docx")  # 注意这里需要绝对路径  相对路径报错了。

    document.paragraphs[2].text 通过下标来访问数据  根据这个特性写了一个  def 来实现   替换


    def modification(paragraphs,find,modif):
        index=-1
        for i in range(0, len(paragraphs)):
            if paragraphs[i].text.find(find) != -1:
                index=i
                break
        if index!= -1:
           temp= paragraphs[index].text
           pos= temp.find(find)
           p =paragraphs[index].clear()
           temp=temp[:pos]+modif+temp[pos+1:-1]
           run = p.add_run(temp)
           font = run.font
           font.size = 540000


    modification(document.paragraphs,"color","739639550")


关键字