目录

基础操作

对象关系

添加样式

中文字体微软雅黑,西文字体Times New Roman

首行缩进

单独设置标题样式

设置超链接

参考文档


基础操作

from docx import Document
from docx.shared import Inches# 创建空文档
document = Document()# 添加标题,设置级别level,0为Title,1或省略为Heading 1,0<=level<=9
document.add_heading('Document Title', 0)
# 添加段落,参数为text=''和style=None
p = document.add_paragraph('A plain paragraph having some ')
# 添加run对象,参数为text=None和style=None,
# run对象有bold(加粗)和italic(斜体)这两个属性
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = Truedocument.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='Intense Quote')document.add_paragraph('first item in unordered list', style='List Bullet'
)
document.add_paragraph('first item in ordered list', style='List Number'
)
# 添加图片
document.add_picture('monty-truth.png', width=Inches(1.25))# 添加表格
records = ((3, '101', 'Spam'),(7, '422', 'Eggs'),(4, '631', 'Spam, spam, eggs, and spam')
)table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for qty, id, desc in records:row_cells = table.add_row().cellsrow_cells[0].text = str(qty)row_cells[1].text = idrow_cells[2].text = descdocument.add_page_break()

对象关系

document.add_paragraph()之后,默认paragraph的内容到第一个run中。

添加样式

中文字体微软雅黑,西文字体Times New Roman

import docx
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn
from docx.shared import Cm, Ptdocument = Document()
# 设置一个空白样式
style = document.styles['Normal']
# 设置西文字体
style.font.name = 'Times New Roman'
# 设置中文字体
style.element.rPr.rFonts.set(qn('w:eastAsia'), '微软雅黑')

首行缩进

# 获取段落样式
paragraph_format = style.paragraph_format
# 首行缩进0.74厘米,即2个字符
paragraph_format.first_line_indent = Cm(0.74)

单独设置标题样式

# 设置标题
title_ = document.add_heading(level=0)
# 标题居中
title_.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 添加标题内容
title_run = title_.add_run(title)
# 设置标题字体大小
title_run.font.size = Pt(14)
# 设置标题西文字体
title_run.font.name = 'Times New Roman'
# 设置标题中文字体
title_run.element.rPr.rFonts.set(qn('w:eastAsia'), '微软雅黑')

设置超链接

def add_hyperlink(paragraph, url, text, color, underline):"""A function that places a hyperlink within a paragraph object.:param paragraph: The paragraph we are adding the hyperlink to.:param url: A string containing the required url:param text: The text displayed for the url:return: The hyperlink object"""# This gets access to the document.xml.rels file and gets a new relation id valuepart = paragraph.partr_id = part.relate_to(url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True)# Create the w:hyperlink tag and add needed valueshyperlink = docx.oxml.shared.OxmlElement('w:hyperlink')hyperlink.set(docx.oxml.shared.qn('r:id'), r_id, )# Create a w:r elementnew_run = docx.oxml.shared.OxmlElement('w:r')# Create a new w:rPr elementrPr = docx.oxml.shared.OxmlElement('w:rPr')# Add color if it is givenif not color is None:c = docx.oxml.shared.OxmlElement('w:color')c.set(docx.oxml.shared.qn('w:val'), color)rPr.append(c)# Remove underlining if it is requestedif not underline:u = docx.oxml.shared.OxmlElement('w:u')u.set(docx.oxml.shared.qn('w:val'), 'none')rPr.append(u)# Join all the xml elements together add add the required text to the w:r elementnew_run.append(rPr)new_run.text = texthyperlink.append(new_run)paragraph._p.append(hyperlink)return hyperlinkdocument = docx.Document()
p = document.add_paragraph()#add a hyperlink with the normal formatting (blue underline)
hyperlink = add_hyperlink(p, 'http://www.google.com', 'Google', None, True)#add a hyperlink with a custom color and no underline
hyperlink = add_hyperlink(p, 'http://www.google.com', 'Google', 'FF8822', False)document.save('demo.docx')

上面的函数是对整段内容直接添加链接,日常使用的时候,超链接多为关键词,或<a>标签的格式,用paragraph和run这两个对象的关系来解决。

比如有文本内容如下,将其中的<a>标签换为超链接:

"""I am trying to add an hyperlink in a MS Word document using docx module for <a href="python.org">Python</a>. Just do it."""

# 判断字段是否为链接
def is_text_link(text):for i in ['http', '://', 'www.', '.com', '.org', '.cn', '.xyz', '.htm']:if i in text:return Trueelse:return False# 对段落中的链接加上超链接
def add_text_link(document, text):paragraph = document.add_paragraph()# 根据<a>标签拆分文本内容text = re.split(r'<a href="|">|</a>',text)keyword = Nonefor i in range(len(text)):# 对非链接和非关键词的内容,通过run直接加入段落中if not is_text_link(text[i]):if text[i] != keyword:paragraph.add_run(text[i])# 对链接和关键词,使用add_hyperlink插入超链接elif i + 1<len(text):url=text[i]keyword=text[i + 1]add_hyperlink(paragraph, url, keyword, None, True)

参考文档

  1. https://python-docx.readthedocs.io/en/latest/index.html
  2. https://github.com/python-openxml/python-docx/issues/74
  3. http://www.warmeng.com/2018/12/02/auto_report/

python-docx操作word文件(*.docx)相关推荐

  1. 在.NET平台用DocX操作Word文件

    最近项目需要输出聘书,聘书就是个Word做成的模板,需要把名字.岗位等文字替换一下. 如果用微软自带的Word编辑DLL,感觉很不好 于是找到了DocX,项目地址https://docx.codepl ...

  2. Python+Word:我已经使用“pip install docx”命令安装了扩展库docx,为什么无法运行书上的代码操作Word文件呢?

    操作Word文件的扩展库名字叫python-docx,不是docx.另外要注意,扩展库python-docx只能操作Word 2007或更新版本的文档,不能处理Word 2003之前的文档.

  3. python docx run断开_别再问我python怎么操作Word了!

    原标题:别再问我python怎么操作Word了! 作者:陈熹 来源:早起Python 在之前的自动化系列文章中,我们分别讲解过python操作Excel利器openpyxl,也讲过python操作PD ...

  4. python入门教程2word-入门干货:Python操作Word文件经验分享

    原标题:入门干货:Python操作Word文件经验分享 导读:Microsoft Word在当前使用中是占有巨大优势的文字处理器,这使得Word专用的档案格式Word 文件(.docx)成为事实上最通 ...

  5. C# DocX操作Word文档(.docx)

    using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Sy ...

  6. pdf文件转word文件docx后缀的简单方法

    pdf文件转word文件docx后缀的简单方法 ![选择打开,浏览 最后,可以免费方便的完成pdf到word的转换.

  7. 用Python批处理将WORD文件转换成PDF格式(工具:win32com模块)

    用Python批处理将WORD文件转换成PDF格式 一.问题分析 key words:批处理.WORD转换PDF.办公自动化 二.材料准备 三.代码实现 ☆其他问题:日常遇到问题,整理笔记不易,欢迎交 ...

  8. Python办公自动化----操作word文档

    用python操作word文档 在Python中,可以使用名为python-docx的三方库来操作word文件,可以使用下面的命令来安装它. 安装三方库 : pip install python-do ...

  9. Java操作word文件的工具选择

    Java操作word文件的工具选择 使用Java语言,创建doc.docx.excel.pdf等文档,并对文档进行一系列操作. Spire.Doc for Java https://blog.csdn ...

  10. jacob.jar 操作word文件 添加水印、图片(附查阅Microsoft Office VBA参考文档方式)

    jacob.jar 操作word文件 添加水印.图片 1.准备jacob.jar包和dll文件 将jacob.jar引入到工程, 64位: 将jacob-1.17-M2-x64.dll 放在C:\Wi ...

最新文章

  1. 使用Mono管理Coyote Linux
  2. 企业架构的过去、现在与未来
  3. 你真的会用java注解吗?
  4. android 程序运行不了,当应用程序在后台运行或不运行时,Android – 推送通知工作不正确...
  5. Linux 查看命令路径 以及相关信息
  6. 关于天线增益、发射角、阵列的一些见解
  7. python tcp通信如何实现多人聊天,Python实现多用户全双工聊天(一对一),python多用户,多用户全双工聊天简陋...
  8. ASP.NET Core 3.x - 为什么采用新的 Endpoint Routing 路由系统
  9. 动态查找表之二叉搜索树
  10. 动态获取textarea后面的p标签_HTML简单标签连起实现的小玩意:
  11. VC++视频教程下载地址
  12. 力扣190.颠倒二进制数
  13. python网络编程学习笔记(6):Web客户端访问
  14. java 利用Future异步获取多线程任务结果
  15. 计算机应用202001常规,2001年4月份全国高等教育自学考试计算机应用基础试题
  16. 【电力】永磁同步电机-自抗扰控制PMSM ADRC附matlab代码
  17. 计算机主板有哪些接口,主板硬盘一般有哪些接口
  18. 全球水深地形模型ETOPO1
  19. shell脚本检查域名证书是否过期
  20. 新冠疫苗预约小程序设计与实现的源码+文档

热门文章

  1. 客快物流大数据项目(一百一十七):网关 Spring Cloud Gateway
  2. 动态规划-leetcode#10-最长回文
  3. 【IoT】硬件产品设计:智能硬件产品开发时间表
  4. 亚信安全防毒墙网络版卸载,联软安全助手(lva_setupfull)卸载
  5. 优思学院|建立六西格玛管理模式的七部曲
  6. 【python安全攻防】python简易端口扫描器
  7. webmatrix如何使用php,用微软的webmatrix配置PHP网站
  8. [深度学习-NPL]ELMO、BERT、GPT学习与总结
  9. 关于RGBFusion无法识别和控制技嘉显卡RGB灯的特殊案例和解决办法
  10. OneNote2007产品密钥及激活方法