使用Python处理Word文件

  • 安装外部模块python-docx
pip install python-docx

1. 从Python看Word文件结构

在python-docx模块中,将Word文件结构分成3层:

  • Document:最高层,代表整个Word文件。
  • Paragraph:一个Word文件由许多段落组成,在Python中,整份文件的定义是Document,这些段落的定义就是Paragraph对象。在Python中,一个段落代表一个
    Paragraph对象,所有段落以Paragraph对象列表方式存在。
  • Run:Word文件要考虑的有字号、字体样式、色彩等,统称为样式。一个Run对象指的是Paragraph对象中相同样式的连续文字,如果文字发生样式变化,Python将以新的Run对象代表。

2. 读取Word文件内容

  • 读取简单word文件
# author:mlnt
# createdate:2022/8/15
import docx  # 导入docx模块# 1.创建docx对象
document = docx.Document('test.docx')# 2.获得Paragraph和Run数量
# 使用len()方法获得Paragraph数量
paragraph_count = len(document.paragraphs)
print(f'段落数:{paragraph_count}')
for i in range(0, paragraph_count):# 获取Paragraph的Run数量paragraph_run_count = len(document.paragraphs[i].runs)  # i为Paragraph编号print(document.paragraphs[i].text)  # 打印Paragraph内容print(document.paragraphs[i].runs[i].text)  # 打印第i段第i个Run内容def getFile(filename):"""读取文件与适度编辑文件"""document = docx.Document(filename)  # 建立Word文件对象content = []for paragraph in document.paragraphs:print(paragraph.text)  # 输出文件所读取的Paragraph内容content.append(paragraph.text)  # 将每一段Paragraph组成列表return '\n\n'.join(content)  # 将列表转成字符串并隔行输出print(getFile('test.docx'))
# 存储文件
document.save('out_test.docx')  # 将文件复制到新文件

test.docx:

out_test.docx

  • 读取含表格的word文档内容
# author:mlnt
# createdate:2022/8/15
import docx  # 导入docx模块
from docx.document import Document
from docx.oxml import CT_P, CT_Tbl
from docx.table import _Cell, Table, _Row
from docx.text.paragraph import Paragraphdef iter_block_items(parent):"""依次遍历文档内容按文档顺序生成对父级中每个段落和表子级的引用。每个返回值都是表或段落的实例。父对象通常是对主文档对象的引用,但也适用于_Cell对象,它本身可以包含段落和表格。:param parent::return:"""# 判断传入的是否为word文档对象,是则获取文档内容的全部子对象if isinstance(parent, Document):parent_elm = parent.element.body# 判断传入的是否为单元格,是则获取单元格内全部子对象elif isinstance(parent, _Cell):parent_elm = parent.tc# 判断是否为表格行elif isinstance(parent, _Row):parent_elm = parent.trelse:raise ValueError("something's not right")# 遍历全部子对象for child in parent_elm.iterchildren():# 判断是否为段落,是则返回段落对象if isinstance(child, CT_P):yield Paragraph(child, parent)# 判断是否为表格,是则返回表格对象if isinstance(child, CT_Tbl):yield Table(child, parent)# 1.创建docx对象
document = docx.Document('test.docx')
# 遍历word文档,最后调用函数没有返回值时停止遍历
for block in iter_block_items(document):# 判断是否为段落if isinstance(block, Paragraph):print(block.text)# 判断是否为表格elif isinstance(block, Table):for row in block.rows:row_data = []for cell in row.cells:for paragraph in cell.paragraphs:row_data.append(paragraph.text)print("\t".join(row_data))

测试文档:

读取效果:

3. 创建文件内容

  • 创建docx对象

    # 1.创建docx对象
    document = docx.Document()
    
  • 设置页面

    # 设置页眉
    run_header = document.sections[0].header.paragraphs[0].add_run("test")
    document.sections[0].header.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER  # 居中对齐
    
  • 添加标题

    # 2.添加标题
    """
    add_heading():建立标题
    - document.add_heading('content_of_heading', level=n)
    """
    document.add_heading('侠客行', level=1)  # 标题1格式
    document.add_heading('李白', level=2)   # 标题2格式
    
  • 添加段落

    # 3.添加段落
    # 创建段落对象
    """
    add_paragraph():建立段落Paragraph内容
    - document.add_paragraph('paragraph_content')
    """
    paragraph_object = document.add_paragraph('赵客缦胡缨,吴钩霜雪明。')
    document.add_paragraph('银鞍照白马,飒沓如流星。')
    document.add_paragraph('十步杀一人,千里不留行。')
    document.add_paragraph('事了拂衣去,深藏身与名。')
    document.add_paragraph('闲过信陵饮,脱剑膝前横。')
    document.add_paragraph('将炙啖朱亥,持觞劝侯嬴。')
    document.add_paragraph('三杯吐然诺,五岳倒为轻。')
    document.add_paragraph('眼花耳热后,意气素霓生。')
    document.add_paragraph('救赵挥金槌,邯郸先震惊。')
    document.add_paragraph('千秋二壮士,烜赫大梁城。')
    document.add_paragraph('纵死侠骨香,不惭世上英。')
    document.add_paragraph('谁能书阁下,白首太玄经。')
    prior_paragraph_object = paragraph_object.insert_paragraph_before('')  # 在paragraph前插入新段落
    
  • 建立Run内容,设置样式

    # 4.建立Run内容
    """
    Paragraph是由Run组成,使用add_run()方法可以在Paragraph中插入内容,语法如下:
    paragraph_object.add_run('run_content')
    """
    run1 = prior_paragraph_object.add_run('*'*13)
    run2 = prior_paragraph_object.add_run('%'*13)
    # 设置Run的样式
    """
    bold: 加粗
    italic:斜体
    underline:下划线
    strike:删除线
    """
    run1.bold = True
    run2.underline = True# 设置段落居中对齐
    for i in range(len(document.paragraphs)):document.paragraphs[i].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER  # 居中对齐
    
  • 添加换页符

    # 5.添加换页符
    # add_page_break()
    document.add_page_break()
    
  • 插入图片

    # 6.插入图片
    # add_picture(),调整图片宽高需导入docx.shared模块
    document.add_picture('libai.jpeg', width=Pt(200), height=Pt(300))# 设置居中对齐
    document.paragraphs[len(document.paragraphs)-1].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER  # 居中对齐
    
  • 创建表格,添加数据并设置简单样式

    # 7.创建表格
    """
    add_table(rows=n, cols=m)
    """
    table = document.add_table(rows=2, cols=5)
    # 添加表格内容
    # 添加第1行数据
    row = table.rows[0]
    row.cells[0].text = '姓名'
    row.cells[1].text = '字'
    row.cells[2].text = '号'
    row.cells[3].text = '所处时代'
    row.cells[4].text = '别称'
    # 添加第2行数据
    row = table.rows[1]
    row.cells[0].text = '李白'
    row.cells[1].text = '太白'
    row.cells[2].text = '青莲居士'
    row.cells[3].text = '唐朝'
    row.cells[4].text = '诗仙'# 插入行
    new_row = table.add_row()  # 增加表格行
    new_row.cells[0].text = '白居易'
    new_row.cells[1].text = '乐天'
    new_row.cells[2].text = '香山居士'
    new_row.cells[3].text = '唐朝'
    new_row.cells[4].text = '诗魔'# 插入列
    new_column = table.add_column(width=Inches(1))  # 增加表格列
    new_column.cells[0].text = '代表作'
    new_column.cells[1].text = '《侠客行》、《静夜思》'
    new_column.cells[2].text = '《长恨歌》、《琵琶行》'# 计算表格的rows和cols的长度
    rows = len(table.rows)
    cols = len(table.columns)
    print(f'rows: {rows}')
    print(f'columns: {cols}')# 打印表格内容
    # for row in table.rows:
    #     for cell in row.cells:
    #         print(cell.text)# 设置表格样式
    # table.style = 'LightShading-Accent1'
    # UserWarning: style lookup by style_id is deprecated. Use style name as key instead.
    table.style = 'Light Shading Accent 1'
    # 循环将每一行,每一列都设置为居中
    for r in range(rows):for c in range(cols):table.cell(r, c).vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER  # 垂直居中table.cell(r, c).paragraphs[0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER  # 水平居中
    
  • 设置页码并保存

    # 设置页码
    add_page_number(document.sections[0].footer.paragraphs[0])
    # 保存文件
    document.save('test2.docx')
    
  • 设置页码的代码(page_num.py)

    from docx import Document
    from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
    from docx.oxml import OxmlElement, nsdef create_element(name):return OxmlElement(name)def create_attribute(element, name, value):element.set(ns.qn(name), value)def add_page_number(paragraph):paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTERpage_run = paragraph.add_run()t1 = create_element('w:t')create_attribute(t1, 'xml:space', 'preserve')t1.text = 'Page 'page_run._r.append(t1)page_num_run = paragraph.add_run()fldChar1 = create_element('w:fldChar')create_attribute(fldChar1, 'w:fldCharType', 'begin')instrText = create_element('w:instrText')create_attribute(instrText, 'xml:space', 'preserve')instrText.text = "PAGE"fldChar2 = create_element('w:fldChar')create_attribute(fldChar2, 'w:fldCharType', 'end')page_num_run._r.append(fldChar1)page_num_run._r.append(instrText)page_num_run._r.append(fldChar2)of_run = paragraph.add_run()t2 = create_element('w:t')create_attribute(t2, 'xml:space', 'preserve')t2.text = ' of 'of_run._r.append(t2)fldChar3 = create_element('w:fldChar')create_attribute(fldChar3, 'w:fldCharType', 'begin')instrText2 = create_element('w:instrText')create_attribute(instrText2, 'xml:space', 'preserve')instrText2.text = "NUMPAGES"fldChar4 = create_element('w:fldChar')create_attribute(fldChar4, 'w:fldCharType', 'end')num_pages_run = paragraph.add_run()num_pages_run._r.append(fldChar3)num_pages_run._r.append(instrText2)num_pages_run._r.append(fldChar4)
    
  • 完整代码

    import docx
    from docx.enum.table import WD_TABLE_ALIGNMENT, WD_CELL_VERTICAL_ALIGNMENT
    from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
    from docx.shared import Pt, Inches
    from page_num import add_page_number# 1.创建docx对象
    document = docx.Document()# 设置页眉
    run_header = document.sections[0].header.paragraphs[0].add_run("test")
    document.sections[0].header.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER  # 居中对齐
    print(len(document.sections))# 2.添加标题
    """
    add_heading():建立标题
    - document.add_heading('content_of_heading', level=n)
    """
    document.add_heading('侠客行', level=1)  # 标题1格式
    document.add_heading('李白', level=2)   # 标题2格式# 3.添加段落
    # 创建段落对象
    """
    add_paragraph():建立段落Paragraph内容
    - document.add_paragraph('paragraph_content')
    """
    paragraph_object = document.add_paragraph('赵客缦胡缨,吴钩霜雪明。')
    document.add_paragraph('银鞍照白马,飒沓如流星。')
    document.add_paragraph('十步杀一人,千里不留行。')
    document.add_paragraph('事了拂衣去,深藏身与名。')
    document.add_paragraph('闲过信陵饮,脱剑膝前横。')
    document.add_paragraph('将炙啖朱亥,持觞劝侯嬴。')
    document.add_paragraph('三杯吐然诺,五岳倒为轻。')
    document.add_paragraph('眼花耳热后,意气素霓生。')
    document.add_paragraph('救赵挥金槌,邯郸先震惊。')
    document.add_paragraph('千秋二壮士,烜赫大梁城。')
    document.add_paragraph('纵死侠骨香,不惭世上英。')
    document.add_paragraph('谁能书阁下,白首太玄经。')
    prior_paragraph_object = paragraph_object.insert_paragraph_before('')  # 在paragraph前插入新段落
    # 4.建立Run内容
    """
    Paragraph是由Run组成,使用add_run()方法可以在Paragraph中插入内容,语法如下:
    paragraph_object.add_run('run_content')
    """
    run1 = prior_paragraph_object.add_run('*'*13)
    run2 = prior_paragraph_object.add_run('%'*13)
    # 设置Run的样式
    """
    bold: 加粗
    italic:斜体
    underline:下划线
    strike:删除线
    """
    run1.bold = True
    run2.underline = True# 设置段落居中对齐
    for i in range(len(document.paragraphs)):document.paragraphs[i].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER  # 居中对齐# 5.添加换页符
    # add_page_break()
    document.add_page_break()
    # print(len(document.paragraphs))
    # 6.插入图片
    # add_picture(),调整图片宽高需导入docx.shared模块
    document.add_picture('libai.jpeg', width=Pt(200), height=Pt(300))# 设置居中对齐
    document.paragraphs[len(document.paragraphs)-1].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER  # 居中对齐# 7.创建表格
    """
    add_table(rows=n, cols=m)
    """
    table = document.add_table(rows=2, cols=5)
    # 添加表格内容
    # 添加第1行数据
    row = table.rows[0]
    row.cells[0].text = '姓名'
    row.cells[1].text = '字'
    row.cells[2].text = '号'
    row.cells[3].text = '所处时代'
    row.cells[4].text = '别称'
    # 添加第2行数据
    row = table.rows[1]
    row.cells[0].text = '李白'
    row.cells[1].text = '太白'
    row.cells[2].text = '青莲居士'
    row.cells[3].text = '唐朝'
    row.cells[4].text = '诗仙'# 插入行
    new_row = table.add_row()  # 增加表格行
    new_row.cells[0].text = '白居易'
    new_row.cells[1].text = '乐天'
    new_row.cells[2].text = '香山居士'
    new_row.cells[3].text = '唐朝'
    new_row.cells[4].text = '诗魔'# 插入列
    new_column = table.add_column(width=Inches(1))  # 增加表格列
    new_column.cells[0].text = '代表作'
    new_column.cells[1].text = '《侠客行》、《静夜思》'
    new_column.cells[2].text = '《长恨歌》、《琵琶行》'# 计算表格的rows和cols的长度
    rows = len(table.rows)
    cols = len(table.columns)
    print(f'rows: {rows}')
    print(f'columns: {cols}')# 打印表格内容
    # for row in table.rows:
    #     for cell in row.cells:
    #         print(cell.text)# 设置表格样式
    # table.style = 'LightShading-Accent1'
    # UserWarning: style lookup by style_id is deprecated. Use style name as key instead.
    table.style = 'Light Shading Accent 1'
    # 循环将每一行,每一列都设置为居中
    for r in range(rows):for c in range(cols):table.cell(r, c).vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER  # 垂直居中table.cell(r, c).paragraphs[0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER  # 水平居中# 设置页码
    add_page_number(document.sections[0].footer.paragraphs[0])
    # 保存文件
    document.save('test2.docx')
    

    效果:


参考:

  • https://blog.csdn.net/m0_62184088/article/details/122522009
  • https://www.cnpython.com/qa/1290238
  • https://blog.csdn.net/qq_39147299/article/details/125544621
  • https://blog.csdn.net/hwwaizs/article/details/121186150
  • https://blog.csdn.net/I_fole_you/article/details/121028608
  • python-docx官方文档:https://python-docx.readthedocs.io/en/latest/
  • https://blog.csdn.net/qq_38870145/article/details/124076591
  • https://www.cnblogs.com/wl0924/p/16531087.html
  • https://blog.csdn.net/qq_39905917/article/details/83503486
  • https://qa.1r1g.com/sf/ask/2046849521/

使用Python处理Word文件相关推荐

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

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

  2. Python处理word文件

    python对word文件进行读写和复制 import win32conimport win32com.clientimport os #读取word文件def readWoldFile(path): ...

  3. 使用python读取word文件里的表格信息

    在企查查查询企业信息的时候,得到了一些word文件,里面有些控股企业的数据放在表格里,需要我们将其提取出来. word文件看起来很复杂,不方便进行结构化.实际上,一个word文档中大概有这么几种类型的 ...

  4. Python提取Word文件中的目录标题保存为Excel文件

    from docx import Document from openpyxl import Workbook from openpyxl.styles import Alignment, Borde ...

  5. Python检查Word文件中包含特定关键字的所有页码

    推荐教材:<Python程序设计基础与应用>(ISBN:9787111606178),董付国,机械工业出版社 图书详情: 配套资源: 用书教师可以联系董老师获取教学大纲.课件.源码.教案. ...

  6. 用Python将word文件转换成html(转)

    用Python将word文件转换成html 序 最近公司一个客户大大购买了一堆医疗健康方面的科普文章,希望能放到我们正在开发的健康档案管理软件上.客户大大说,要智能推送!要掌握节奏!要深度学习!要让用 ...

  7. python获取word页数_python,_如何在 Linux 上使用 Python 读取 word 文件信息(如页数)?,python - phpStudy...

    如何在 Linux 上使用 Python 读取 word 文件信息(如页数)? R.T. doc 是二进制文件,Python 如何进行读取呢? .docx 可用 python-docx 读取,但如何读 ...

  8. python word处理_妙用Python将word文件转换成html 方法超简单

    什么方法可以将word文件转换成html,找了一圈,没有发现合适的应用可以把word或indd转化成干净的html.机缘巧合,无意间听说python很擅长文本处理,用Python将word文件转换成h ...

  9. 使用python修改word文件

    通过使用Python修改Word文件 import osimport win32com from self import self from win32com.client import Dispat ...

最新文章

  1. QQ web api
  2. 1.5 关于这门课-深度学习-Stanford吴恩达教授
  3. 百兆以太网传输距离_新品推荐 16+2G口百兆/千兆监控接入型非标PoE交换机!
  4. python的数组属性_[Python]numpy use array属性,pythonnumpy,使用,数组
  5. 【leetcode79】Single Number III
  6. 输出100之间的所有质数(素数)
  7. 安装php项目后图片路径不对,解决织梦CMS栏目绑定二级域名后图片不显示,路径错误办法...
  8. chromium thirt_party skia编译shared_liberary
  9. 抢购为什么难,需要怎么做?
  10. AnimeGAN v2:动漫风格化GAN
  11. Mockplus: 让小白产品经理上手就用的原型图设计工具
  12. 微信小程序真机调试方法出现问题
  13. knex mysql 操作_手把手教你用express + mysql + knex 做个 todoList
  14. 力扣 1818. 绝对差值和 数学 二分
  15. ui设计培训机构内课程包括哪些板块|优漫动游
  16. POJ - 1723 Soldiers 士兵站队 排序+中位数
  17. 高数考研归纳 - 微分学 - 一元微分学
  18. 站外促销折扣码设置教程
  19. K均值算法【K-means】
  20. c语言循环彩灯课程设计,单片机节日彩灯课程设计,从两边向中间点亮依次循环不止。亮灭时间为0.25S,用一个开关控制彩灯的工作...

热门文章

  1. 【机器学习】线性回归——岭回归解决过拟合问题(理论+图解+公式推导)
  2. 如何开通阿里云短信业务
  3. U盘数据恢复怎么做?分享4个恢复方法!
  4. iphone中使用国内邮箱设置方法
  5. VSCODE下载太慢(教你一招解决)
  6. Function Point Estimation 功能点估算是一种用来估算项目大小的技术。
  7. 一个不像程序员的程序员,褚霸:IT男得有品位才能做出极致的产品
  8. HDU 4081 最小生成树(或者次小生成树)
  9. OSChina 周六乱弹 —— 吉祥如意的 2015
  10. H5中<img>的srcset、size属性及<picture>介绍