python docx设置标题中文字体run2.element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑')报错AttributeError: 'NoneType' object has no attribute 'rFonts'


写一个用python批量生成docx的程序,出现问题

我的代码

   p2 = document.add_paragraph()
    run2 = p2.add_run(i+': ')   
    run2.element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑')
    run2.font.size = Pt(16)
    run2.font.name = "微软雅黑"  
    run2.font.bold = True

报错

run2.element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑')
AttributeError: 'NoneType' object has no attribute 'rFonts'

解决方法

    p2 = document.add_paragraph()
    run2 = p2.add_run(i+': ')   
    run2.font.name = "微软雅黑"  
    run2.element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑')
    run2.font.size = Pt(16)
    # run2.font.name = "微软雅黑"  
    run2.font.bold = True
通过资料发现,run2.font.name = "微软雅黑" 必须放在run2.element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑')的前面,
即需要先设置字体名字这个属性,再进行中文字体设置,完美运行


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM