
python-docx 简介python-docx 是 Python 操作 Word 文档最常用的库。它的处理方式是面向对象的,会把 Word 文档中的各种元素都看作对象:Document- 整个 Word 文档Paragraph- 文档中的段落Run- 段落中的文字块(可以设置不同格式)这三级结构是最基础的概念。如果文档中有表格,结构会稍微复杂一点:表格可以看成Document → Table → Row/Column → Cell这样的四级结构,跟 Excel 很像。安装 python-docx在 PyCharm 的终端里输入:pip install python-docx看到Successfully installed就表示安装成功了。课程准备下载课程资源文件:[点击下载 word.zip]解压后放到D:\自动化\word目录下,结构如下:提前准备好文件夹,方便后面跟着练习。新建与保存 Word 文档from docx import Document # 创建一个空文档 document = Document() # 保存到指定路径 document.save(r'D:\自动化\word\道德经.docx')运行后,在D:\自动化\word目录下就会多出一个道德经.docx文件。因为是空文档,打开里面是空白的。注意:安装的是python-docx,但导入时用import docx。写入 Word 文档下面这段代码演示了往 Word 里写各种内容:from docx import Document from docx.shared import Inches, Cm # 英寸和厘米单位 # 打开刚才创建的文档 file_path = r'D:\自动化\word\道德经.docx' document = Document(file_path) # 添加文档标题(level=0 是文档标题) document.add_heading('道德经', 0) # 添加段落 p = document.add_paragraph('道可道,非常道;名可名,非常名。') # 在同一段落里追加不同格式的文字 p.add_run('无名,天地之始,').bold = True # 粗体 p.add_run('有名,') # 默认格式 p.add_run('万物之母。').italic = True # 斜体 # 添加一级标题 document.add_heading('故常无欲,', level=1) # 添加带样式的段落 document.add_paragraph('以观其妙,', style='Intense Quote') # 添加项目符号列表 document.add_paragraph('常有欲,以观其徼。', style='List Bullet') # 添加编号列表 document.add_paragraph('此两者,同出而异名,同谓之玄,玄之又玄,众妙之门。', style='List Number') document.add_paragraph('所以说,学Python,学得妙。', style='List Number') # 添加图片(三种方式) img_path = r'D:\自动化\word\girl.png' document.add_picture(img_path) # 原图大小 document.add_picture(img_path, width=Inches(1.25)) # 指定宽度 document.add_picture(img_path, width=Cm(5), height=Cm(5)) # 指定宽高 # 准备表格数据 records = ( (1, '李白', '诗仙'), (2, '杜甫', '诗圣'), (3, '白居易', '香山居士, 与元稹并称元白, 与刘禹锡合称刘白') ) # 添加表格(1行3列,带网格样式) table = document.add_table(rows=1, cols=3, style='Table Grid') # 填充表头 hdr_cells = table.rows[0].cells hdr_cells[0].text = '序号' hdr_cells[1].text = '姓名' hdr_cells[2].text = '描述' # 动态添加数据行 for id, name, desc in records: row_cells = table.add_ro